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.

1049 lines
42 KiB

6 years ago
  1. //
  2. // RecipientFormViewController.swift
  3. // GMERemittance
  4. //
  5. // Created by Fm-user on 12/22/17.
  6. // Copyright © 2017 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import UIKit
  9. import SDWebImage
  10. protocol PaginationDelegate {
  11. func updateCurrentIndex(status:String,recipient: Recipient,pageNumber: Int)
  12. }
  13. class RecipientFormViewController: UIViewController {
  14. @IBOutlet weak var scrollView: UIScrollView!
  15. @IBOutlet weak var textFieldFirstName: UITextField!
  16. @IBOutlet weak var textFieldMiddleName: UITextField!
  17. @IBOutlet weak var textFieldLastName: UITextField!
  18. @IBOutlet weak var textFieldCountry: UITextField!
  19. @IBOutlet weak var textFieldState: UITextField!
  20. @IBOutlet weak var textFieldDistrict: UITextField!
  21. @IBOutlet weak var textFieldCity: UITextField!
  22. @IBOutlet weak var textFieldAddress: UITextField!
  23. @IBOutlet weak var textFieldRelation: UITextField!
  24. @IBOutlet weak var textFieldMobile: UITextField!
  25. @IBOutlet weak var textFieldEmail: UITextField!
  26. @IBOutlet weak var textFieldTransferReason: UITextField!
  27. private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
  28. private var pickerView = UIPickerView()
  29. private var arrayOftextFields: [UITextField]!
  30. private var activeTextField: UITextField?
  31. private var selectedIndexFor: [String: Int] = [String: Int]()
  32. public var paginationDelegate: PaginationDelegate!
  33. private var recipientviewmodel: RecipientViewModel!
  34. private var createNewRecipient: Bool!
  35. var noInternetDialog: Bool?
  36. var pageNumber: Int?
  37. var recipient: Recipient?
  38. var newRecipient: Recipient?
  39. var pickerData: [String] = [String]()
  40. var pickerDataState: [String] = [String]()
  41. var pickerDataDistrict: [String] = [String]()
  42. var pickerDataRelation: [String] = [String]()
  43. var pickerDataReason: [String] = [String]()
  44. var countryResult = false
  45. var stateResult = false
  46. var districtResult = false
  47. var relationResult = false
  48. var trasferReasonResult = false
  49. private var updateParameters: [String: String] = [String: String] ()
  50. public static var recipientConnectionTimeOutConnectionCheck = 0
  51. var pickerIndex: Int = 0
  52. func createRecipientObject(recipientId: String) -> Recipient{
  53. var recipient = Recipient()
  54. recipient.recipientId = recipientId
  55. recipient.firstName = textFieldFirstName.text
  56. recipient.middleName = textFieldMiddleName.text
  57. recipient.lastName = textFieldLastName.text
  58. recipient.city = textFieldCity.text
  59. recipient.address = textFieldAddress.text
  60. recipient.mobileNumber = textFieldMobile.text
  61. recipient.email = textFieldEmail.text
  62. if createNewRecipient! {
  63. if let index = selectedIndexFor["country"]{
  64. if recipientviewmodel.getCountryId(index: index) != "N/A"{
  65. recipient.country = recipientviewmodel.getCountryId(index: index)
  66. }
  67. }
  68. if let index = selectedIndexFor["relation"]{
  69. recipient.relation = recipientviewmodel.getRelationValue(index: index)
  70. }
  71. if let index = selectedIndexFor["transferReason"]{
  72. recipient.reason = recipientviewmodel.getTransferReasonValue(index: index)
  73. }
  74. if let index = selectedIndexFor["state"]{
  75. recipient.state = recipientviewmodel.getStateValue(index: index)
  76. }
  77. if let index = selectedIndexFor["district"]{
  78. recipient.district = recipientviewmodel.getDistrictValue(index: index)
  79. }
  80. } else {
  81. if let index = selectedIndexFor["country"]{
  82. recipient.country = recipientviewmodel.getCountryName(index: index)
  83. }
  84. if let index = selectedIndexFor["country"]{
  85. recipient.countryId = recipientviewmodel.getCountryId(index: index)
  86. }
  87. if let index = selectedIndexFor["relation"]{
  88. recipient.relationId = recipientviewmodel.getRelationValue(index: index)
  89. }
  90. if let index = selectedIndexFor["relation"]{
  91. recipient.relation = recipientviewmodel.getRelationName(index: index)
  92. }
  93. if let index = selectedIndexFor["transferReason"]{
  94. recipient.reasonId = recipientviewmodel.getTransferReasonValue(index: index)
  95. }
  96. if let index = selectedIndexFor["transferReason"]{
  97. recipient.reason = recipientviewmodel.getTransferReasonName(index: index)
  98. }
  99. if let index = selectedIndexFor["state"]{
  100. recipient.state = recipientviewmodel.getState(index: index)
  101. }
  102. if let index = selectedIndexFor["state"]{
  103. recipient.stateId = recipientviewmodel.getStateValue(index: index)
  104. }
  105. if let index = selectedIndexFor["district"]{
  106. recipient.district = recipientviewmodel.getDistrict(index: index)
  107. }
  108. if let index = selectedIndexFor["district"]{
  109. recipient.districtId = recipientviewmodel.getDistrictValue(index: index)
  110. }
  111. }
  112. return recipient
  113. }
  114. @IBAction func createOrUpdateRecipient(_ sender: Any) {
  115. startLoading()
  116. let textFieldArray = [textFieldFirstName.text, textFieldLastName.text, textFieldCountry.text, textFieldState.text, textFieldDistrict.text, textFieldCity.text, textFieldAddress.text, textFieldRelation.text, textFieldMobile.text, textFieldTransferReason.text]
  117. guard recipientviewmodel.allFieldsFilled(arrayofInfo: textFieldArray as! [String]) else {
  118. self.popUpMessageError(value: 11, message: "Please fill all the fields")
  119. stopLoading()
  120. return
  121. }
  122. if createNewRecipient {
  123. recipientviewmodel.createRecipient()
  124. } else {
  125. recipientviewmodel.updateRecipient(recipientId: (recipient?.recipientId)!, updateParams: updateParameters)
  126. }
  127. activeTextField?.resignFirstResponder()
  128. }
  129. func setPageNumber(pageNumber: Int){
  130. self.pageNumber = pageNumber;
  131. }
  132. @objc func clearKeyboard() {
  133. activeTextField?.resignFirstResponder()
  134. }
  135. override func viewDidLoad() {
  136. super.viewDidLoad()
  137. selectedIndexFor["country"] = 0
  138. selectedIndexFor["transferReason"] = 0
  139. selectedIndexFor["relation"] = 0
  140. selectedIndexFor["state"] = 0
  141. selectedIndexFor["district"] = 0
  142. setUpNavBar(id: 201, title: "Send Money")
  143. noInternetDialog = false
  144. startLoading()
  145. /// TODO: first transaction free message Display
  146. /* tracktransactionviewmodel.internetConnection.value = nil
  147. tracktransactionviewmodel.internetConnection.bind { [unowned self] in
  148. guard $0 != nil else {
  149. return
  150. }
  151. self.enableUserInteractions()
  152. self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
  153. self.popUpMessage(value: 15)
  154. }
  155. tracktransactionviewmodel.fetchTransactionList(recipientId: "", recipientName: "", transactionType: "", startDate: "", endDate: "")
  156. tracktransactionviewmodel.transactionListObtained.bind{ [unowned self] in
  157. guard $0 != nil else {
  158. return
  159. }
  160. self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
  161. self.enableUserInteractions()
  162. guard $0! else {
  163. self.popUpMessageError(value: 10, message: self.tracktransactionviewmodel.getErrorMessage())
  164. return
  165. }
  166. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  167. let transactionStatus = appDelegate.firstTranscationStatusForProfileForm
  168. if self.tracktransactionviewmodel.getCount() == 0 && transactionStatus == true {
  169. self.popUpMessage(value: 9)
  170. }
  171. }*/
  172. RecipientListViewController.recipientStatus = false
  173. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
  174. NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
  175. let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(clearKeyboard))
  176. view.addGestureRecognizer(tap)
  177. arrayOftextFields = [textFieldFirstName, textFieldMiddleName, textFieldLastName, textFieldCountry, textFieldState, textFieldDistrict, textFieldCity, textFieldAddress, textFieldRelation, textFieldMobile, textFieldEmail, textFieldTransferReason]
  178. for textField in arrayOftextFields {
  179. textField.delegate = self
  180. }
  181. pickerView.delegate = self
  182. pickerView.dataSource = self
  183. guard recipient == nil else {
  184. createNewRecipient = false
  185. recipientviewmodel = RecipientViewModel(recipient: recipient!)
  186. setUpAnotherLoginListener(genericviewmodel: recipientviewmodel)
  187. if let firstName = recipient?.firstName{
  188. textFieldFirstName.text = firstName
  189. }
  190. if let middleName = recipient?.middleName{
  191. textFieldMiddleName.text = middleName
  192. }
  193. if let lastName = recipient?.lastName{
  194. textFieldLastName.text = lastName
  195. }
  196. if let district = recipient?.district{
  197. textFieldDistrict.text = district
  198. }
  199. if let city = recipient?.city{
  200. textFieldCity.text = city
  201. }
  202. if let state = recipient?.state{
  203. textFieldState.text = state
  204. }
  205. if let address = recipient?.address{
  206. textFieldAddress.text = address
  207. }
  208. if let mobileNumber = recipient!.mobileNumber{
  209. textFieldMobile.text = mobileNumber
  210. }
  211. if let email = recipient?.email{
  212. textFieldEmail.text = email
  213. }
  214. if let relation = recipient?.relation{
  215. textFieldRelation.text = relation
  216. }
  217. if let reason = recipient?.reason{
  218. textFieldTransferReason.text = reason
  219. }
  220. recipientviewmodel.recipientConnectionTimeOut.value = nil
  221. /**
  222. connection timeout
  223. */
  224. recipientviewmodel.recipientConnectionTimeOut.bind { [unowned self] in
  225. guard $0 != nil else {
  226. return
  227. }
  228. self.stopLoading()
  229. if RecipientFormViewController.recipientConnectionTimeOutConnectionCheck == 0{
  230. RecipientFormViewController.recipientConnectionTimeOutConnectionCheck = RecipientFormViewController.recipientConnectionTimeOutConnectionCheck+1
  231. self.popUpMessage(value: 27)
  232. self.textFieldCountry.text = ""
  233. self.textFieldCountry.leftViewMode = UITextFieldViewMode.never
  234. }
  235. }
  236. self.startLoading()
  237. internetCheck()
  238. self.setUpListener()
  239. self.cddListBindCall()
  240. fetchCountryList()
  241. recipientviewmodel.fetchCDDListFor(cddName: cddCode.Province.rawValue, param: ["countryId": (recipient?.countryId)!])
  242. if let stateId = recipient?.stateId {
  243. recipientviewmodel.fetchCDDListFor(cddName: cddCode.District.rawValue, param: [ "countryId": (recipient?.countryId)!, "provinceId": stateId])
  244. }
  245. fetchRelationList()
  246. fetchTransferReason()
  247. return
  248. }
  249. createNewRecipient = true
  250. recipientviewmodel = RecipientViewModel()
  251. recipientviewmodel.recipientConnectionTimeOut.value = nil
  252. /**
  253. connection timeout
  254. */
  255. recipientviewmodel.recipientConnectionTimeOut.bind { [unowned self] in
  256. guard $0 != nil else {
  257. return
  258. }
  259. self.stopLoading()
  260. if RecipientFormViewController.recipientConnectionTimeOutConnectionCheck == 0{
  261. RecipientFormViewController.recipientConnectionTimeOutConnectionCheck = RecipientFormViewController.recipientConnectionTimeOutConnectionCheck+1
  262. self.popUpMessage(value: 27)
  263. self.textFieldCountry.text = ""
  264. self.textFieldCountry.leftViewMode = UITextFieldViewMode.never
  265. }
  266. }
  267. setUpAnotherLoginListener(genericviewmodel: recipientviewmodel)
  268. internetCheck()
  269. self.setUpListener()
  270. cddListBindCall()
  271. fetchCountryList()
  272. fetchTransferReason()
  273. fetchRelationList()
  274. }
  275. /**
  276. Api request to fetch list of country
  277. */
  278. func fetchCountryList(){
  279. if recipientviewmodel.getCountryList().count == 0 {
  280. recipientviewmodel.fetchListOfCountry()
  281. }
  282. }
  283. /**
  284. Api request to fetch transfer reason
  285. */
  286. func fetchTransferReason() {
  287. if recipientviewmodel.getTransferReason().count == 0 {
  288. recipientviewmodel.fetchCDDListFor(cddName: cddCode.TransferReason.rawValue, param: ["": ""])
  289. }
  290. }
  291. /**
  292. Api request to fetch states
  293. */
  294. func fetchStates() {
  295. recipientviewmodel.fetchCDDListFor(cddName: cddCode.Province.rawValue, param: ["countryId": recipientviewmodel.getCountryId(index: selectedIndexFor["country"]!)])
  296. }
  297. /**
  298. Api request to fetch district
  299. */
  300. func fetchDistrict() {
  301. recipientviewmodel.fetchCDDListFor(cddName: cddCode.District.rawValue, param: [ "countryId": recipientviewmodel.getCountryId(index: selectedIndexFor["country"]!), "provinceId": recipientviewmodel.getStateValue(index: selectedIndexFor["state"]!)])
  302. }
  303. /**
  304. Api request to fetch list of relation
  305. */
  306. func fetchRelationList() {
  307. if recipientviewmodel.getRelationList().count == 0 {
  308. recipientviewmodel.fetchCDDListFor(cddName: cddCode.Relation.rawValue, param: ["": ""])
  309. }
  310. }
  311. override func viewDidDisappear(_ animated: Bool) {
  312. RecipientListViewController.recipientStatus = false
  313. }
  314. /**
  315. Check internet connection
  316. */
  317. func internetCheck(){
  318. recipientviewmodel.internetConnection.bind { [unowned self] in
  319. guard $0 != nil else {
  320. return
  321. }
  322. if !self.noInternetDialog! {
  323. self.stopLoading()
  324. self.popUpMessage(value: 15)
  325. self.textFieldCountry.text = ""
  326. self.textFieldCountry.leftViewMode = UITextFieldViewMode.never
  327. }
  328. self.stopLoading()
  329. self.noInternetDialog = true
  330. }
  331. }
  332. /**
  333. bind call for recipient both create and update
  334. */
  335. func setUpListener() {
  336. recipientviewmodel.recipientCreatedUpdated.bind { [unowned self] in
  337. guard $0 != nil else {
  338. return
  339. }
  340. guard $0! else {
  341. //self.popUpMessageError(value: 10, message: self.recipientviewmodel.getErrorMessage())
  342. self.stopLoading()
  343. return
  344. }
  345. if self.createNewRecipient {
  346. self.newRecipient = self.recipientviewmodel.getCreatedRecipient()
  347. self.addRecipient()
  348. } else {
  349. self.recipientUpdateMessage()
  350. }
  351. }
  352. /**
  353. bind call for country list
  354. */
  355. recipientviewmodel.cddCountryListAvailable.bind { [weak self] in
  356. guard $0 != nil else {
  357. return
  358. }
  359. guard $0! else {
  360. // self?.popUpMessageError(value: 10, message: (self?.recipientviewmodel.getErrorMessage())!)
  361. return
  362. }
  363. if self?.recipient != nil {
  364. self?.pickerData = (self?.recipientviewmodel.getCountryNameList())!
  365. if let countryId = self?.recipient?.countryId{
  366. let countryIndex = self?.recipientviewmodel.getIndex(id: countryId)
  367. if let url = self?.recipientviewmodel.getCountryFlagUrlList()[countryIndex!]{
  368. let url = url
  369. self?.selectedIndexFor["country"] = countryIndex
  370. self?.showCountryWithFlag(textField: (self?.textFieldCountry)!, url: url, index: countryIndex!)
  371. }
  372. }
  373. }
  374. self?.countryResult = true
  375. if (self?.createNewRecipient)! {
  376. self?.stopLoading()
  377. } else {
  378. self?.checkResult()
  379. }
  380. }
  381. }
  382. /**
  383. bind call for cddList
  384. - Transfer reason
  385. - relation
  386. - Province
  387. - District
  388. */
  389. func cddListBindCall(){
  390. recipientviewmodel.cddListAvailable.bind { [weak self] in
  391. guard $0 != nil else {
  392. return
  393. }
  394. guard $0! != 0 else {
  395. // self?.popUpMessageError(value: 10, message: (self?.recipientviewmodel.getErrorMessage())!)
  396. return
  397. }
  398. self?.pickerDataRelation = (self?.recipientviewmodel.getRelationList())!
  399. self?.pickerDataReason = (self?.recipientviewmodel.getTransferReason())!
  400. if !(self?.createNewRecipient)! {
  401. switch $0!{
  402. case 1:
  403. self?.pickerDataReason = (self?.recipientviewmodel.getTransferReason())!
  404. if self?.textFieldTransferReason.text != ""{
  405. if let reasonIndex = self?.pickerDataReason.index(of: (self?.textFieldTransferReason.text)!) {
  406. self?.selectedIndexFor["transferReason"] = reasonIndex
  407. }
  408. }
  409. self?.trasferReasonResult = true
  410. case 2:
  411. self?.pickerDataState = (self?.recipientviewmodel.getStateList())!
  412. if self?.textFieldState.text != "" {
  413. if let stateIndex = self?.pickerDataState.index(of: (self?.textFieldState.text)!){
  414. self?.selectedIndexFor["state"] = stateIndex
  415. }
  416. } else {
  417. self?.selectedIndexFor["state"] = 0
  418. }
  419. self?.stateResult = true
  420. case 3:
  421. self?.pickerDataDistrict = (self?.recipientviewmodel.getDistrictList())!
  422. if self?.textFieldDistrict.text != ""{
  423. if let districtIndex = self?.pickerDataDistrict.index(of: (self?.textFieldDistrict.text)!) {
  424. self?.selectedIndexFor["district"] = districtIndex
  425. }
  426. } else {
  427. self?.selectedIndexFor["district"] = 0
  428. }
  429. self?.districtResult = true
  430. case 4:
  431. self?.pickerDataRelation = (self?.recipientviewmodel.getRelationList())!
  432. self?.selectedIndexFor["relation"] = self?.pickerDataRelation.index(of: (self?.textFieldRelation.text)!)
  433. self?.relationResult = true
  434. default:
  435. return
  436. }
  437. }
  438. if (self?.createNewRecipient)! {
  439. self?.stopLoading()
  440. } else {
  441. self?.checkResult()
  442. }
  443. self?.recipientviewmodel.cddListAvailable.value = nil
  444. }
  445. }
  446. /**
  447. To check all result are available or not after multiple api call..
  448. */
  449. func checkResult(){
  450. if countryResult == true &&
  451. stateResult == true &&
  452. districtResult == true &&
  453. relationResult == true &&
  454. trasferReasonResult == true {
  455. stopLoading()
  456. }
  457. }
  458. /**
  459. Disable user interaction while fetching data from api
  460. */
  461. func startLoading(){
  462. disableUserInteractions()
  463. showActivityIndicator(activityIndicator: activityIndicator)
  464. }
  465. /**
  466. Enable user interaction while fetching data from api
  467. */
  468. func stopLoading(){
  469. self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
  470. self.enableUserInteractions()
  471. }
  472. func addRecipient(){
  473. let alert = UIAlertController(title:"Add", message:"New Receiver profile added successfully" , preferredStyle: .actionSheet)
  474. present(alert, animated: true, completion: nil)
  475. let when = DispatchTime.now() + 2
  476. DispatchQueue.main.asyncAfter(deadline: when){
  477. alert.dismiss(animated: true, completion: nil)
  478. if let recipientId = self.self.recipientviewmodel.getCreatedRecipient().recipientId, let pageNumber = self.pageNumber{
  479. self.paginationDelegate.updateCurrentIndex(status: "add",recipient: self.createRecipientObject(recipientId:recipientId),pageNumber: pageNumber)
  480. }
  481. self.navigationController?.popViewController(animated: true)
  482. }
  483. }
  484. func recipientUpdateMessage(){
  485. let alert = UIAlertController(title:"Update", message:"Receiver profile updated successfully" , preferredStyle: .actionSheet)
  486. present(alert, animated: true, completion: nil)
  487. let when = DispatchTime.now() + 2
  488. DispatchQueue.main.asyncAfter(deadline: when){
  489. // your code with delay
  490. alert.dismiss(animated: true, completion: nil)
  491. if let recipientId = self.recipient?.recipientId , let pageNumber = self.pageNumber{
  492. self.paginationDelegate.updateCurrentIndex(status: "update",recipient: self.createRecipientObject(recipientId: (recipientId)),pageNumber: pageNumber)
  493. }
  494. self.navigationController?.popViewController(animated: true)
  495. }
  496. }
  497. @objc func keyboardWillShow(notification: NSNotification) {
  498. var userInfo = notification.userInfo!
  499. var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
  500. keyboardFrame = self.view.convert(keyboardFrame, from: nil)
  501. var contentInset:UIEdgeInsets = self.scrollView.contentInset
  502. contentInset.bottom = keyboardFrame.size.height + 70
  503. self.scrollView.contentInset = contentInset
  504. }
  505. @objc func keyboardWillHide(notification: NSNotification) {
  506. self.scrollView.contentInset = UIEdgeInsets.zero
  507. }
  508. //Doing Picker view button
  509. func pickUp(_ textField : UITextField){
  510. // UIPickerView
  511. self.pickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
  512. self.pickerView.delegate = self
  513. self.pickerView.dataSource = self
  514. //self.pickerView.backgroundColor = UIColor.white
  515. textField.inputView = self.pickerView
  516. // ToolBar
  517. let toolBar = UIToolbar()
  518. toolBar.barStyle = .default
  519. toolBar.isTranslucent = true
  520. toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
  521. toolBar.sizeToFit()
  522. // Adding Button ToolBar
  523. let customButton = UIButton()
  524. var cancel = UIBarButtonItem()
  525. customButton.setTitle("Done", for: .normal)
  526. customButton.addTarget(self, action: #selector(doneClick), for: .touchUpInside)
  527. customButton.setTitleColor(UIColor(hex : 0xED1C24), for: .normal)
  528. customButton.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
  529. cancel = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(self.cancelClick))
  530. cancel.tintColor = UIColor.black
  531. let doneButton = UIBarButtonItem(customView: customButton)
  532. let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
  533. toolBar.setItems([cancel,spaceButton, doneButton], animated: false)
  534. toolBar.isUserInteractionEnabled = true
  535. textField.inputAccessoryView = toolBar
  536. }
  537. @objc func doneClick() {
  538. activeTextField?.resignFirstResponder()
  539. self.noInternetDialog = false
  540. if activeTextField == textFieldCountry {
  541. textFieldState.text = ""
  542. textFieldDistrict.text = ""
  543. pickerDataState.removeAll()
  544. pickerDataDistrict.removeAll()
  545. selectedIndexFor["state"] = 0
  546. selectedIndexFor["country"] = pickerIndex
  547. startLoading()
  548. if let index = selectedIndexFor["country"]{
  549. recipientviewmodel.setCountryId(referenceIndex: index)
  550. }
  551. if let index = selectedIndexFor["country"]{
  552. showCountryWithFlag(textField: activeTextField!, url: recipientviewmodel.getCountryFlagUrl(index: index), index: index)
  553. }
  554. if let index = selectedIndexFor["country"]{
  555. updateParameters["country"] = recipientviewmodel.getCountryIdList()[index]
  556. }
  557. fetchStates()
  558. } else if activeTextField == textFieldTransferReason {
  559. if pickerDataReason.count > 0 {
  560. if let transferReason = selectedIndexFor["transferReason"]{
  561. recipientviewmodel.setTransferReason(referenceIndex: transferReason)
  562. }
  563. if let transferReasonIndex = selectedIndexFor["transferReason"]{
  564. textFieldTransferReason.text = pickerDataReason[transferReasonIndex]
  565. }
  566. }
  567. if let transferReason = selectedIndexFor["transferReason"]{
  568. updateParameters["reason"] = recipientviewmodel.getTransferReasonValueList()[transferReason]
  569. }
  570. } else if activeTextField == textFieldRelation {
  571. if pickerDataRelation.count > 0 {
  572. if let relationIndex = selectedIndexFor["relation"]{
  573. recipientviewmodel.setRelation(referenceIndex: relationIndex)
  574. textFieldRelation.text = pickerDataRelation[relationIndex]
  575. }
  576. }
  577. if let relationIndex = selectedIndexFor["relation"]{
  578. updateParameters["relation"] = recipientviewmodel.getRelationValueList()[relationIndex]
  579. }
  580. } else if activeTextField == textFieldState {
  581. textFieldDistrict.text = ""
  582. pickerDataDistrict.removeAll()
  583. selectedIndexFor["district"] = 0
  584. if pickerDataState.count > 0{
  585. if let state = selectedIndexFor["state"]{
  586. recipientviewmodel.setState(referenceIndex: state)
  587. textFieldState.text = pickerDataState[state]
  588. }
  589. }
  590. startLoading()
  591. fetchDistrict()
  592. if let state = selectedIndexFor["state"]{
  593. updateParameters["state"] = recipientviewmodel.getStateValueList()[state]
  594. }
  595. } else if activeTextField == textFieldDistrict {
  596. if pickerDataDistrict.count > 0 {
  597. if let district = selectedIndexFor["district"]{
  598. recipientviewmodel.setDistrict(referenceIndex: district)
  599. textFieldDistrict.text = pickerDataDistrict[district]
  600. updateParameters["district"] = recipientviewmodel.getDistrictValueList()[district]
  601. }
  602. }
  603. }
  604. }
  605. @objc func cancelClick(){
  606. activeTextField?.resignFirstResponder()
  607. }
  608. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  609. if segue.identifier == "paymentMethod" {
  610. let paymentViewController = segue.destination as! PaymentMethodViewController
  611. paymentViewController.recipient = newRecipient
  612. }
  613. }
  614. override func didReceiveMemoryWarning() {
  615. super.didReceiveMemoryWarning()
  616. }
  617. }
  618. extension RecipientFormViewController: UITextFieldDelegate {
  619. func textFieldDidBeginEditing(_ textField: UITextField) {
  620. activeTextField = textField
  621. if textField == textFieldCountry ||
  622. textField == textFieldRelation ||
  623. textField == textFieldTransferReason ||
  624. textField == textFieldState ||
  625. textField == textFieldDistrict {
  626. if createNewRecipient {
  627. switch textField {
  628. case textFieldCountry:
  629. pickerData = recipientviewmodel.getCountryNameList()
  630. case textFieldRelation:
  631. pickerDataRelation = recipientviewmodel.getRelationList()
  632. case textFieldTransferReason:
  633. pickerDataReason = recipientviewmodel.getTransferReason()
  634. case textFieldState:
  635. pickerDataState = recipientviewmodel.getStateList()
  636. case textFieldDistrict:
  637. pickerDataDistrict = recipientviewmodel.getDistrictList()
  638. default:
  639. return
  640. }
  641. }
  642. pickerView.reloadAllComponents()
  643. switch textField {
  644. case textFieldCountry:
  645. guard pickerData.count > 0 else {
  646. textField.resignFirstResponder()
  647. self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
  648. return
  649. }
  650. if let index = selectedIndexFor["country"]{
  651. pickUp(textField)
  652. pickerView.selectRow(index, inComponent: 0, animated: true)
  653. recipientviewmodel.setCountryId(referenceIndex: index)
  654. }
  655. case textFieldRelation:
  656. guard pickerDataRelation.count > 0 else {
  657. textField.resignFirstResponder()
  658. self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
  659. return
  660. }
  661. pickUp(textField)
  662. if textFieldRelation.text != "" {
  663. if let index = pickerDataRelation.index(of: textFieldRelation.text!){
  664. self.selectedIndexFor["relation"] = index
  665. pickerView.selectRow(index, inComponent: 0, animated: true)
  666. }
  667. }
  668. case textFieldTransferReason:
  669. guard pickerDataReason.count > 0 else {
  670. textField.resignFirstResponder()
  671. self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
  672. return
  673. }
  674. pickUp(textField)
  675. if textFieldTransferReason.text != "" {
  676. if let index = pickerDataReason.index(of: textFieldTransferReason.text!){
  677. self.selectedIndexFor["transferReason"] = index
  678. pickerView.selectRow(index, inComponent: 0, animated: true)
  679. }
  680. }
  681. case textFieldState:
  682. guard pickerDataState.count > 0 else {
  683. textField.resignFirstResponder()
  684. self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
  685. return
  686. }
  687. pickUp(textField)
  688. if textFieldState.text != ""{
  689. if let index = pickerDataState.index(of: textFieldState.text!){
  690. self.selectedIndexFor["state"] = index
  691. pickerView.selectRow(index, inComponent: 0, animated: true)
  692. }
  693. }
  694. case textFieldDistrict:
  695. guard pickerDataDistrict.count > 0 else {
  696. textField.resignFirstResponder()
  697. self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
  698. return
  699. }
  700. pickUp(textField)
  701. if textFieldDistrict.text != ""{
  702. if let index = pickerDataDistrict.index(of: textFieldDistrict.text!) {
  703. self.selectedIndexFor["district"] = index
  704. pickerView.selectRow(index, inComponent: 0, animated: true)
  705. }
  706. }
  707. default:
  708. return
  709. }
  710. }
  711. }
  712. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  713. let index: Int = arrayOftextFields.index(of: textField)!
  714. guard index < (arrayOftextFields.count-1) else {
  715. textField.resignFirstResponder()
  716. return true
  717. }
  718. arrayOftextFields[index+1].becomeFirstResponder()
  719. return true
  720. }
  721. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  722. let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
  723. switch textField {
  724. case textFieldFirstName:
  725. recipientviewmodel.updateFirstName(firstName: newString)
  726. case textFieldMiddleName:
  727. recipientviewmodel.updateMiddleName(middleName: newString)
  728. case textFieldLastName:
  729. recipientviewmodel.updateLastName(lastName: newString)
  730. case textFieldCity:
  731. recipientviewmodel.updateCity(city: newString)
  732. case textFieldAddress:
  733. recipientviewmodel.updateAddress(address: newString)
  734. case textFieldMobile:
  735. recipientviewmodel.updateMobile(mobile: newString)
  736. case textFieldEmail:
  737. recipientviewmodel.updateEmail(email: newString)
  738. default:
  739. return false
  740. }
  741. return true
  742. }
  743. func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
  744. switch textField {
  745. case textFieldState:
  746. if textFieldCountry.text == "" {
  747. textFieldCountry.resignFirstResponder()
  748. textField.resignFirstResponder()
  749. self.popUpMessageInfo(value: 16, title: "Select Country!", message: "Please select the country first.")
  750. return false
  751. } else {
  752. return true
  753. }
  754. case textFieldDistrict:
  755. if textFieldState.text == ""{
  756. textFieldCountry.resignFirstResponder()
  757. textFieldState.resignFirstResponder()
  758. self.popUpMessageInfo(value: 16, title: "Select State/Province!", message: "Please select the State/Province first")
  759. return false
  760. } else {
  761. return true
  762. }
  763. default:
  764. return true
  765. }
  766. }
  767. func textFieldDidEndEditing(_ textField: UITextField) {
  768. if recipient != nil {
  769. switch textField {
  770. case textFieldFirstName:
  771. updateParameters["firstName"] = textField.text!
  772. case textFieldMiddleName:
  773. updateParameters["middleName"] = textField.text!
  774. case textFieldLastName:
  775. updateParameters["lastName"] = textField.text!
  776. case textFieldCountry:
  777. if let index = selectedIndexFor["country"]{
  778. updateParameters["country"] = recipientviewmodel.getCountryId(index: index)
  779. }
  780. case textFieldState:
  781. if let index = selectedIndexFor["state"]{
  782. updateParameters["state"] = recipientviewmodel.getStateValue(index: index)
  783. }
  784. case textFieldDistrict:
  785. if let index = selectedIndexFor["district"]{
  786. updateParameters["district"] = recipientviewmodel.getDistrictValue(index: index)
  787. }
  788. case textFieldCity:
  789. updateParameters["city"] = textField.text!
  790. case textFieldAddress:
  791. updateParameters["address"] = textField.text!
  792. case textFieldRelation:
  793. if let index = selectedIndexFor["relation"]{
  794. updateParameters["relation"] = recipientviewmodel.getRelationValue(index: index)
  795. }
  796. case textFieldMobile:
  797. updateParameters["mobileNumber"] = textField.text!
  798. case textFieldEmail:
  799. updateParameters["email"] = textField.text!
  800. case textFieldTransferReason:
  801. if let index = selectedIndexFor["transferReason"]{
  802. updateParameters["transferReason"] = recipientviewmodel.getTransferReasonValue(index: index)
  803. }
  804. default:
  805. return
  806. }
  807. }
  808. }
  809. }
  810. extension RecipientFormViewController: UIPickerViewDataSource, UIPickerViewDelegate {
  811. func numberOfComponents(in pickerView: UIPickerView) -> Int {
  812. return 1
  813. }
  814. func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
  815. if activeTextField == textFieldCountry {
  816. return pickerData.count
  817. } else if activeTextField == textFieldState{
  818. return pickerDataState.count
  819. } else if activeTextField == textFieldDistrict{
  820. return pickerDataDistrict.count
  821. } else if activeTextField == textFieldRelation{
  822. return pickerDataRelation.count
  823. } else if activeTextField == textFieldTransferReason {
  824. return pickerDataReason.count
  825. } else {
  826. return 0
  827. }
  828. }
  829. func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
  830. if activeTextField == textFieldCountry {
  831. return pickerData[row]
  832. } else if activeTextField == textFieldState{
  833. return pickerDataState[row]
  834. } else if activeTextField == textFieldDistrict {
  835. return pickerDataDistrict[row]
  836. }else if activeTextField == textFieldRelation{
  837. return pickerDataRelation[row]
  838. } else if activeTextField == textFieldTransferReason{
  839. return pickerDataReason[row]
  840. } else {
  841. return ""
  842. }
  843. }
  844. func showCountryWithFlag(textField: UITextField, url: String, index: Int) {
  845. let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
  846. let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
  847. imageView.center = paddingView.center
  848. if let flagUrl = URL(string: url) {
  849. imageView.sd_setImage(with: flagUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  850. }
  851. paddingView.addSubview(imageView)
  852. textField.leftViewMode = UITextFieldViewMode.always
  853. textField.leftView = paddingView
  854. textField.text = pickerData[index]
  855. }
  856. func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
  857. if activeTextField == textFieldCountry {
  858. pickerIndex = row
  859. } else if activeTextField == textFieldState{
  860. selectedIndexFor["state"] = row
  861. } else if activeTextField == textFieldDistrict {
  862. selectedIndexFor["district"] = row
  863. } else if activeTextField == textFieldRelation{
  864. selectedIndexFor["relation"] = row
  865. } else if activeTextField == textFieldTransferReason{
  866. selectedIndexFor["transferReason"] = row
  867. }
  868. }
  869. func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
  870. return 60
  871. }
  872. func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
  873. var myImageView: UIImageView?
  874. let myView = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.bounds.width - 30, height: 60))
  875. let myLabel = UILabel(frame: CGRect(x: 60, y: 0, width: pickerView.bounds.width - 90, height: 60 ))
  876. myView.addSubview(myLabel)
  877. if activeTextField == textFieldCountry{
  878. myLabel.text = pickerData[row]
  879. myImageView = UIImageView(frame: CGRect(x: 0, y: 15, width: 40, height: 40))
  880. myImageView?.sd_setImage(with:URL(string: self.recipientviewmodel.getCountryFlagUrl(index: row)), placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
  881. myView.addSubview(myImageView!)
  882. } else if activeTextField == textFieldState {
  883. myLabel.text = pickerDataState[row]
  884. } else if activeTextField == textFieldDistrict {
  885. myLabel.text = pickerDataDistrict[row]
  886. } else if activeTextField == textFieldRelation {
  887. myLabel.text = pickerDataRelation[row]
  888. } else if activeTextField == textFieldTransferReason{
  889. myLabel.text = pickerDataReason[row]
  890. }
  891. return myView
  892. }
  893. }