//
//  PTPickViewController.swift
//  iOSPrinterDemo
//
//  Created by ios on 2018/5/21.
//  Copyright © 2018年 Mellow. All rights reserved.
//

import UIKit

typealias selectedChaTypeClosure = (_ characterStr:String) -> Void

class PTPickViewController: UIViewController {

    @IBOutlet weak var pickView: UIPickerView!
    
    @IBOutlet weak var toolBar: UIToolbar!
    
    var characterTypeClosure : selectedChaTypeClosure?
    
    static func showCharacterTypeVC(_ options:[String],selectedClosure:@escaping selectedChaTypeClosure) {
        guard let temp = AppWindow.rootViewController as? UINavigationController else {
            return
        }
        let picker = PTPickViewController()
        picker.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        picker.view.frame = temp.view.bounds
        picker.options = options
        picker.characterTypeClosure = selectedClosure
        temp.addChild(picker)
        temp.view.addSubview(picker.view)
    }
    
    var options = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        view.backgroundColor = UIColor.white.withAlphaComponent(0.5)
        configureToolBar()
        
    }

    func configureToolBar() -> Void {
        
        let fixedSpace = UIBarButtonItem.init(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        fixedSpace.width = 10
        let cancelItem = UIBarButtonItem.init(title: "取消", style: .done, target: self, action: #selector(PTPickViewController.cancelItemAction))
        let space = UIBarButtonItem.init(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let pickItem = UIBarButtonItem.init(title: "确定", style: .done, target: self, action: #selector(PTPickViewController.pickItemAction))
        toolBar.items = [fixedSpace,cancelItem,space,pickItem,fixedSpace]
    }
 

}

extension PTPickViewController {
    
    @objc func cancelItemAction() {
        view.removeFromSuperview()
        removeFromParent()
    }
    
    @objc func pickItemAction() {
        if options.count > pickView.selectedRow(inComponent: 0) {
            characterTypeClosure!(options[pickView.selectedRow(inComponent: 0)])
        }
        view.removeFromSuperview()
        removeFromParent()
    }
    
}

extension PTPickViewController : UIPickerViewDelegate,UIPickerViewDataSource {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        return options.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        return options[row]
    }
    
}















