//
//  SearchView.swift
//  SYMobilePortal
//
//  Created by xiejiangbo on 2018/4/26.
//  Copyright © 2018年 yin chen. All rights reserved.
//

import UIKit
import CoreLocation
class SearchView: UIView,CLLocationManagerDelegate,UITextFieldDelegate {
//    var dituBtn = UIButton.init()
//    var menhuLabel = UILabel.init()
//    var searchTextField = UITextField.init()
//    var addBtn = UIButton.init()
    var addBlock:selectBlock!
    var locationManager : CLLocationManager!
//    lazy var lacationManager : CLLocationManager = {
//        let lacationManager = CLLocationManager()
//        lacationManager.distanceFilter = kCLDistanceFilterNone
//        //self.lacationManager.desiredAccuracy = 1
//        lacationManager.desiredAccuracy = kCLLocationAccuracyBest
//        lacationManager.requestAlwaysAuthorization()
//
//        lacationManager.startUpdatingLocation()
//        return lacationManager;
//    }()
    func initLacationManager()  {
        if CLLocationManager .locationServicesEnabled() {
            locationManager = CLLocationManager.init()
            locationManager.delegate = self
            locationManager.requestAlwaysAuthorization()
            locationManager.requestWhenInUseAuthorization()
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.distanceFilter = 5.0
            locationManager.startUpdatingLocation()
        }
    }
    lazy var dituBtn : UIButton = {
        //let dituBtn = UIButton.init(frame: CGRect(x:13*WHIDTH_RATIO(), y: 13*HEIGHT_RATIO(), width:15*WHIDTH_RATIO() , height:19*HEIGHT_RATIO() ))
        let dituBtn = UIButton.init(frame: CGRect(x:13*WHIDTH_RATIO(), y: 13, width:15*WHIDTH_RATIO() , height:19 ))
        dituBtn.setBackgroundImage(UIImage.init(named: "pin_image"), for: .normal)
        return dituBtn;
    }()
    lazy var menhuLabel : UILabel = {
        //let menhuLabel = UILabel.init(frame: CGRect(x:32*WHIDTH_RATIO(), y: 16*HEIGHT_RATIO(), width:getTexWidth(textStr: "上药门户", font: UIFont.systemFont(ofSize: 25.0*WHIDTH_RATIO()), height: 14*HEIGHT_RATIO()) , height:14*HEIGHT_RATIO() ))
        let menhuLabel = UILabel.init(frame: CGRect(x:32*WHIDTH_RATIO(), y: 16, width:getTexWidth(textStr: "上药门户", font: UIFont.systemFont(ofSize: 15.0), height: 14) , height:14 ))
        //menhuLabel.font = UIFont.systemFont(ofSize: 13.0*WHIDTH_RATIO())
        menhuLabel.font = UIFont.systemFont(ofSize: 13.0)
        //menhuLabel.text = "上海"
        menhuLabel.textColor = UIColor.white
        return menhuLabel;
    }()
    lazy var searchTextField : UITextField = {
//        let searchTextField = UITextField.init(frame: CGRect(x:90*WHIDTH_RATIO(), y: 7*HEIGHT_RATIO(), width: SCREEN_WHIDTH()-(90+45)*WHIDTH_RATIO() , height:30*HEIGHT_RATIO() ))
        let searchTextField = UITextField.init(frame: CGRect(x:90*WHIDTH_RATIO(), y: 7, width: SCREEN_WHIDTH()-(90+55)*WHIDTH_RATIO() , height:30 ))
        searchTextField.placeholder = "搜索"
        searchTextField.font = UIFont.systemFont(ofSize: 14)
        searchTextField.setValue(UIFont.systemFont(ofSize: 14), forKeyPath: "_placeholderLabel.font")
        searchTextField.textColor = blackTitleColor
        searchTextField.background = UIImage.init(named: "searchTextField_Bagimage")
        searchTextField.borderStyle = .none
        //let leftSearchView = UIImageView.init(frame: CGRect(x:0, y: 7*HEIGHT_RATIO(), width: 30*WHIDTH_RATIO() , height:14*HEIGHT_RATIO() ))
        let leftSearchView = UIImageView.init(frame: CGRect(x:0, y: 7, width: 30*WHIDTH_RATIO() , height:14 ))
        leftSearchView.image = UIImage.init(named: "search_image")
        leftSearchView.contentMode = .scaleAspectFit
        searchTextField.leftView = leftSearchView
        searchTextField.leftViewMode = .always
        searchTextField.delegate = self
        return searchTextField;
    }()
    lazy var addBtn : UIButton = {
        let addBtn = UIButton.init(frame: CGRect(x:SCREEN_WHIDTH()-35*WHIDTH_RATIO(), y: 12*HEIGHT_RATIO(), width:25*WHIDTH_RATIO() , height:25*HEIGHT_RATIO() ))
        addBtn.setBackgroundImage(UIImage.init(named: "add_image"), for: .normal)
        addBtn.addTarget(self, action: #selector(addAction), for: .touchUpInside)
        //addBtn.backgroundColor = UIColor.red
        return addBtn;
    }()
    @objc func addAction(){
        self.addBlock()
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        addInitView()
        initLacationManager()
    }
    func addInitView() {
        self.backgroundColor = UIColor.clear
        self.addSubview(dituBtn)
        self.addSubview(menhuLabel)
        self.addSubview(searchTextField)
        //self.addSubview(addBtn)
        addBtn.center = searchTextField.center
    }
   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let curLoc:CLLocation = locations.first!
//        print("经度："+String(curLoc.coordinate.longitude)+" 纬度："+String(curLoc.coordinate.latitude))
        //print("高度："+String(curLoc.altitude)+"    垂直精确度："+String(curLoc.verticalAccuracy))
        //print("垂直精确度："+String(curLoc.verticalAccuracy))
        //print("楼层高度："+String(describing: curLoc.floor?.level))
        let geoCoder = CLGeocoder.init()
        geoCoder.reverseGeocodeLocation(curLoc) {[weak self] (placemarks, error) in
            if error != nil {
                return
            }
            for placemark in placemarks! {
                let address:NSDictionary = placemark.addressDictionary! as NSDictionary
                if (!JSONSerialization.isValidJSONObject(address)) {
                    print("无法解析出JSONString")
                    return
                }
//                let data : NSData! = try? JSONSerialization.data(withJSONObject: address, options: []) as NSData!
//                let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
                //print(JSONString ?? String())
                //print(address.object(forKey: "Country") ?? String())
                //print(address.object(forKey: "State") ?? String())
                //print(address.object(forKey: "City") ?? String())
                let arr = address.object(forKey: "FormattedAddressLines") as! NSArray
                //print(arr[0])
                AccountInfo.sharedInstance().address = arr[0] as? String
                self?.menhuLabel.text = address.object(forKey: "City") as? String
                self?.locationManager.stopUpdatingLocation()
            }
        }
    }
   
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
    }
    
    
}
