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.

533 lines
19 KiB

6 years ago
  1. //
  2. // AgentBankViewController.swift
  3. // GMERemittance
  4. //
  5. // Created by FMI-12 on 2/2/18.
  6. // Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import UIKit
  9. import MapKit
  10. class AgentBankViewController: UIViewController {
  11. @IBOutlet weak var tableViewAgent: UITableView!
  12. var selectedCell:Int?
  13. var isSelect:Bool?
  14. private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
  15. private var previousIndex: Int = 0
  16. private var selectedIndex: Int = 10000
  17. private var tableRowIndex: Int?
  18. /// To get data fron sendmoney agentlocation tap
  19. var sendMoneyAgentLocationStatus:Bool = false
  20. var selectedCountry: String = ""
  21. @IBOutlet weak var searchTextField: UITextField!
  22. private var agentCountryList = [AgentCountryList]()
  23. private var agentPayoutList = [AgentModel]()
  24. var agentCell: AgentTableViewCell?
  25. var agentViewModel = AgentViewModel()
  26. @IBOutlet weak var bgViewSearchBar: UIView!
  27. private var pickerView: UIPickerView = UIPickerView()
  28. public static var agentConnectionTimeOutCheck = 0
  29. override func viewWillAppear(_ animated: Bool) {
  30. self.tabBarController?.navigationController?.navigationBar.barTintColor = UIColor(hex:0xEC1C24)
  31. setUpAnotherLoginListener(genericviewmodel: agentViewModel)
  32. }
  33. override func viewDidLoad() {
  34. super.viewDidLoad()
  35. if sendMoneyAgentLocationStatus {
  36. setUpNavBar(id: 206, title: "Agent")
  37. } else {
  38. setUpNavBar(id: 202,title: "")
  39. }
  40. setTextFieldAndPickerViewDelegate()
  41. setTapListenerInBgView()
  42. tableViewAgent.tableFooterView = UIView()
  43. self.tableViewAgent.delegate = self
  44. self.tableViewAgent.dataSource = self
  45. self.tableViewAgent.estimatedRowHeight = 119
  46. self.tableViewAgent.rowHeight = UITableViewAutomaticDimension
  47. tableViewAgent.sectionIndexColor = UIColor.darkGray
  48. tableViewAgent.sectionIndexBackgroundColor = UIColor(hex: 0xe7edf2)
  49. agentViewModel.agentConnectionTimeOut.value = nil
  50. /**
  51. connection timeout
  52. */
  53. agentViewModel.agentConnectionTimeOut.bind { [unowned self] in
  54. guard $0 != nil else {
  55. return
  56. }
  57. self.stopLoading()
  58. if AgentBankViewController.agentConnectionTimeOutCheck == 0{
  59. AgentBankViewController.agentConnectionTimeOutCheck = AgentBankViewController.agentConnectionTimeOutCheck+1
  60. self.popUpMessage(value: 40)
  61. }
  62. }
  63. agentViewModel.internetConnection.value = nil
  64. /**
  65. Internet check
  66. */
  67. agentViewModel.internetConnection.bind { [unowned self] in
  68. guard $0 != nil else {
  69. return
  70. }
  71. self.enableUserInteractions()
  72. self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
  73. self.popUpMessage(value: 15)
  74. }
  75. /**
  76. Update the country list
  77. */
  78. agentViewModel.agentCountryListAvailable.bind { [weak self] in
  79. guard $0 != nil else {
  80. return
  81. }
  82. self?.stopLoading()
  83. guard $0! else {
  84. self?.stopLoading()
  85. //self.popUpMessageError(value: 10, message: self.agentViewModel.getErrorMessage());
  86. return
  87. }
  88. self?.stopLoading()
  89. self?.setAgentCountryList()
  90. }
  91. startLoading()
  92. self.agentViewModel.fetchListOfCountry()
  93. /**
  94. Update the agent location
  95. */
  96. agentViewModel.agentLocationBool.bind { [unowned self] in
  97. guard $0 != nil else {
  98. return
  99. }
  100. self.stopLoading()
  101. guard $0! else {
  102. self.stopLoading()
  103. //self.popUpMessageError(value: 10, message: self.agentViewModel.getErrorMessage());
  104. return
  105. }
  106. self.stopLoading()
  107. self.setAgentLocationList()
  108. }
  109. }
  110. /**
  111. Add Tap gesture in Search bar
  112. */
  113. func setTapListenerInBgView(){
  114. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(AgentBankViewController.openPickerView))
  115. tap.cancelsTouchesInView = false
  116. bgViewSearchBar.addGestureRecognizer(tap)
  117. }
  118. /**
  119. To display Picker view
  120. */
  121. @objc func openPickerView(){
  122. if agentCountryList.count > 0{
  123. self.setPickerViewRowAsSelected()
  124. self.searchTextField.becomeFirstResponder()
  125. }
  126. }
  127. /**
  128. set the country list
  129. */
  130. func setAgentCountryList(){
  131. self.agentCountryList = agentViewModel.getCountryList()
  132. self.requestPayoutList(requestType: "first")
  133. }
  134. /**
  135. Get Agent location address
  136. - return: address list
  137. */
  138. func getAgentLocationAddress() -> [String]{
  139. var agentArray = [String]()
  140. for agent in agentPayoutList{
  141. if let address = agent.address{
  142. agentArray.append(address)
  143. }
  144. }
  145. return agentArray
  146. }
  147. /**
  148. set the agent location list
  149. */
  150. func setAgentLocationList(){
  151. self.agentPayoutList = agentViewModel.getAgentLocation()
  152. if self.agentPayoutList.count > 0{
  153. self.tableViewAgent.reloadData()
  154. }else{
  155. self.popUpMessageError(value: 10, message: "Payout agent is not available in this location.");
  156. }
  157. }
  158. /**
  159. Dispaly loading indicator
  160. */
  161. func startLoading(){
  162. self.showActivityIndicator(activityIndicator: self.activityIndicator)
  163. self.disableUserInteractions()
  164. }
  165. /**
  166. Hide loading indicator
  167. */
  168. func stopLoading(){
  169. self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
  170. self.enableUserInteractions()
  171. }
  172. /**
  173. Delegate setup
  174. */
  175. func setTextFieldAndPickerViewDelegate(){
  176. searchTextField.delegate = self
  177. searchTextField.delegate = self
  178. pickerView.dataSource = self
  179. pickerView.delegate = self
  180. searchTextField.inputView = pickerView
  181. }
  182. /**
  183. Get country list
  184. - returns: country list
  185. */
  186. func getCountryList() -> [String]{
  187. var countryList = [String]()
  188. if agentCountryList.count > 0 {
  189. for country in self.agentCountryList{
  190. if let countryName = country.country{
  191. countryList.append(countryName)
  192. }
  193. }
  194. return countryList
  195. }else{
  196. }
  197. return countryList
  198. }
  199. /**
  200. Display Picker view
  201. */
  202. @IBAction func dropDownButtonAction(_ sender: Any) {
  203. if getCountryList().count > 0{
  204. self.setPickerViewRowAsSelected()
  205. searchTextField.becomeFirstResponder()
  206. }else{
  207. }
  208. }
  209. /**
  210. Set selected row of country list in picker view
  211. */
  212. func setPickerViewRowAsSelected(){
  213. if let searchText = searchTextField.text{
  214. if let index = self.getCountryList().index(of: searchText){
  215. self.pickerView.selectRow(index, inComponent: 0, animated: true)
  216. }
  217. }
  218. }
  219. @IBAction func searchButtonAction(_ sender: Any) {
  220. if searchTextField.text != ""{
  221. if self.agentCountryList[getCountryList().index(of: searchTextField.text!)!].countryId != nil{
  222. self.performSegue(withIdentifier: "agentSuccessViewController", sender: nil)
  223. }
  224. }
  225. else{
  226. }
  227. }
  228. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  229. if segue.identifier == "agentSuccessViewController" {
  230. let agentSearchViewController = segue.destination as! AgentSearchViewController
  231. agentSearchViewController.countryId = self.agentCountryList[getCountryList().index(of: searchTextField.text!)!].countryId
  232. }
  233. }
  234. //Doing Picker view button
  235. func pickUp(_ textField : UITextField){
  236. // UIPickerView
  237. self.pickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
  238. self.pickerView.delegate = self
  239. self.pickerView.dataSource = self
  240. //self.pickerView.backgroundColor = UIColor.white
  241. textField.inputView = self.pickerView
  242. // ToolBar
  243. let toolBar = UIToolbar()
  244. toolBar.barStyle = .default
  245. toolBar.isTranslucent = true
  246. toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
  247. toolBar.sizeToFit()
  248. // Adding Button ToolBar
  249. let customButton = UIButton()
  250. customButton.setTitle("Done", for: .normal)
  251. customButton.addTarget(self, action: #selector(AgentBankViewController.doneClick), for: .touchUpInside)
  252. customButton.setTitleColor(UIColor(hex : 0xED1C24), for: .normal)
  253. customButton.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
  254. let doneButton = UIBarButtonItem(customView: customButton)
  255. let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
  256. toolBar.setItems([spaceButton, doneButton], animated: false)
  257. toolBar.isUserInteractionEnabled = true
  258. textField.inputAccessoryView = toolBar
  259. }
  260. @objc func doneClick() {
  261. self.searchTextField.resignFirstResponder()
  262. if self.selectedIndex != 10000{
  263. if self.isSelect == true{
  264. self.isSelect = false
  265. searchTextField.leftView = nil
  266. self.requestPayoutList(requestType: "later")
  267. }
  268. }
  269. }
  270. /**
  271. request of country list
  272. - parameter requestType: First(Korea) or later(selected country from picker view)
  273. */
  274. func requestPayoutList(requestType: String){
  275. startLoading()
  276. self.agentPayoutList.removeAll()
  277. if requestType == "later"{
  278. searchTextField.text = getCountryList()[self.selectedIndex]
  279. if let flagUrl = agentCountryList[selectedIndex].flagUrl{
  280. self.downloadImage(url: Foundation.URL(string: flagUrl)!)
  281. } else {
  282. }
  283. let countryId = self.agentCountryList[getCountryList().index(of: searchTextField.text!)!].countryId
  284. agentViewModel.fetchAgentLocation(countryId: countryId!)
  285. }else if requestType == "first"{
  286. if !(selectedCountry.isEmpty) {
  287. selectedCountryFromSendMoney()
  288. } else {
  289. if let countryId = self.agentCountryList[getCountryList().index(of: "South Korea")!].countryId,let flagUrl = self.agentCountryList[getCountryList().index(of: "South Korea")!].flagUrl{
  290. searchTextField.text = self.agentCountryList[getCountryList().index(of: "South Korea")!].country
  291. self.downloadImage(url: Foundation.URL(string: flagUrl)!)
  292. agentViewModel.fetchAgentLocation(countryId: countryId)
  293. }else{
  294. }
  295. }
  296. }
  297. }
  298. /**
  299. To get country Agent List through Sendmoney Page
  300. */
  301. func selectedCountryFromSendMoney(){
  302. if let countrySelectedId = self.agentCountryList[getCountryList().index(of: selectedCountry)!].countryId, let countrySeletedflagUrl = self.agentCountryList[getCountryList().index(of: selectedCountry)!].flagUrl {
  303. searchTextField.text = self.agentCountryList[getCountryList().index(of: selectedCountry)!].country
  304. self.downloadImage(url: Foundation.URL(string:countrySeletedflagUrl)!)
  305. agentViewModel.fetchAgentLocation(countryId: countrySelectedId)
  306. }
  307. }
  308. func getDataFromUrl(url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
  309. URLSession.shared.dataTask(with: url) { data, response, error in
  310. completion(data, response, error)
  311. }.resume()
  312. }
  313. /**
  314. To download image through url
  315. - parameter url: url
  316. */
  317. func downloadImage(url: URL) {
  318. getDataFromUrl(url: url) { data, response, error in
  319. guard let data = data, error == nil else { return }
  320. DispatchQueue.main.async() {
  321. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 30, height: 50))
  322. let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
  323. let image = UIImage(data: data)
  324. imageView.center = paddingView.center
  325. imageView.image = image
  326. paddingView.addSubview(imageView)
  327. self.searchTextField.leftViewMode = UITextFieldViewMode.always
  328. self.searchTextField.leftView = paddingView
  329. }
  330. }
  331. }
  332. }
  333. extension AgentBankViewController: UITableViewDelegate, UITableViewDataSource, AgentTableViewCellDelegate {
  334. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  335. return agentPayoutList.count
  336. }
  337. func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  338. self.tableRowIndex = indexPath.row
  339. agentCell = tableView.dequeueReusableCell(withIdentifier: "agentCell", for: indexPath) as? AgentTableViewCell
  340. agentCell?.layer.borderColor = UIColor(red:0.91, green:0.93, blue:0.95, alpha:1.0).cgColor
  341. agentCell?.layer.borderWidth = 2.5
  342. agentCell?.layer.cornerRadius = 10
  343. agentCell?.clipsToBounds = true
  344. if let name = agentPayoutList[indexPath.row].name {
  345. agentCell?.labelBranchName.text = name
  346. }
  347. if let address = agentPayoutList[indexPath.row].address {
  348. agentCell?.labelBranchAddress.text = address
  349. }
  350. if let phone = agentPayoutList[indexPath.row].phone{
  351. agentCell?.buttonPhoneNumber.setTitle(phone, for: UIControlState.normal)
  352. }else{
  353. agentCell?.buttonPhoneNumber.setTitle(" ", for: UIControlState.normal)
  354. }
  355. agentCell?.buttonMap?.addTarget(self, action:#selector(agentTableViewCellDidTapMap(_:)), for:.touchUpInside)
  356. return agentCell!
  357. }
  358. @objc func agentTableViewCellDidTapMap(_ sender: AgentTableViewCell) {
  359. guard let clickedCell = sender.superview?.superview?.superview as? AgentTableViewCell else {
  360. return
  361. }
  362. let clickedCellIndexPath = tableViewAgent.indexPath(for: clickedCell)
  363. selectedCell = clickedCellIndexPath?.row
  364. let storyboard = UIStoryboard.init(name: "RecipientListViewController", bundle: Bundle.main)
  365. if let agentLocationViewController = storyboard.instantiateViewController(withIdentifier: "agentLocation") as? AgentLocation {
  366. if let lat = agentPayoutList[self.tableRowIndex!].latitude{
  367. if let lng = agentPayoutList[self.tableRowIndex!].longitude{
  368. let latitude = String (lat)
  369. let longitude = String (lng)
  370. agentLocationViewController.latitude = CLLocationDegrees(latitude)
  371. agentLocationViewController.longitude = CLLocationDegrees(longitude)!
  372. self.navigationController!.pushViewController(agentLocationViewController, animated: true)
  373. }
  374. }
  375. else{
  376. self.popUpMessageInfo(value: 16, title: "Location", message: "Map view is not available.")
  377. }
  378. }
  379. }
  380. func sectionIndexTitles(for tableView: UITableView) -> [String]? {
  381. return ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"]
  382. }
  383. func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
  384. let tappedIndex = getAgentLocationAddress().index(where: {$0.prefix(1).uppercased() == title})
  385. if tappedIndex != nil {
  386. self.previousIndex = tappedIndex!
  387. tableView.scrollToRow(at: IndexPath(row: tappedIndex!, section: 0), at: UITableViewScrollPosition.top, animated: true)
  388. }
  389. return previousIndex //Previous index is set so that in case when there is no data for selected title, the screen remains at the previous selection title
  390. }
  391. }
  392. extension AgentBankViewController: UIPickerViewDataSource, UIPickerViewDelegate {
  393. func numberOfComponents(in pickerView: UIPickerView) -> Int {
  394. return 1
  395. }
  396. func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
  397. return getCountryList().count
  398. }
  399. func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
  400. return getCountryList()[row]
  401. }
  402. func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
  403. self.selectedIndex = row
  404. isSelect = true
  405. }
  406. /**
  407. To display image on picker view row
  408. */
  409. func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
  410. var myImageView: UIImageView?
  411. let myView = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.bounds.width - 30, height: 60))
  412. let myLabel = UILabel(frame: CGRect(x: 60, y: 0, width: pickerView.bounds.width - 90, height: 60 ))
  413. myLabel.text = agentCountryList[row].country
  414. myView.addSubview(myLabel)
  415. /// Display country flag on pickerview
  416. myImageView = UIImageView(frame: CGRect(x: 0, y: 15, width: 30, height: 30))
  417. myImageView?.sd_setImage(with:URL(string: self.agentCountryList[row].flagUrl ?? ""), placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  418. myView.addSubview(myImageView!)
  419. return myView
  420. }
  421. func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
  422. return 60
  423. }
  424. }
  425. extension AgentBankViewController: UITextFieldDelegate {
  426. func textFieldDidBeginEditing(_ textField: UITextField) {
  427. self.pickUp(textField)
  428. self.setPickerViewRowAsSelected()
  429. }
  430. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  431. return false
  432. }
  433. func textFieldDidEndEditing(_ textField: UITextField) {
  434. }
  435. }