//
//  SJMapViewController.swift
//  GeliBusinessPlatform
//
//  Created by junye lu on 2020/5/6.
//  Copyright © 2020 junye lu. All rights reserved.
//

import UIKit
import AMapLocationKit
import AMapFoundationKit
import MAMapKit
import AMapSearchKit
import LGButton
import IQKeyboardManagerSwift


protocol SJMapViewControllerDelegate {
    func SJMapViewControllerSelectArd(adr:String,cityData:String,loc:String)
}
class SJMapViewController: UIViewController,NavBarViewDelegate,AMapLocationManagerDelegate,MAMapViewDelegate,AMapSearchDelegate,UISearchBarDelegate,SearchBarViewDelegate,UITableViewDelegate,UITableViewDataSource, CLLocationManagerDelegate{
    var isPPH = false
    var delegate:SJMapViewControllerDelegate?
    let navbar = NavBarView(frame: NavCGRect)
    var mapView: MAMapView!
    var search: AMapSearchAPI!
    var lat:CLLocationDegrees = 0
    var lng:CLLocationDegrees = 0
    var manger:CLLocationManager = CLLocationManager()
    
    var adrArr:Array<AMapPOI> = []
    
    var searchV : SearchBarView? = nil
    var listView:UITableView? = nil
    
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden = true
        IQKeyboardManager.shared.shouldPlayInputClicks = true
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.shouldResignOnTouchOutside = true
    }
    var alreadySelect = false
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        manger.stopUpdatingLocation()
        if alreadySelect {
            alreadySelect = false
            initMapView(lat: lat, lng: lng)
            initSearch()
        }else{
            let location = locations.last
            lat = location?.coordinate.latitude as! CLLocationDegrees
            lng = location?.coordinate.longitude as! CLLocationDegrees
            let coo = JZLocationConverter.wgs84(toGcj02: CLLocationCoordinate2D(latitude: lat, longitude: lng))
            initMapView(lat: coo.latitude, lng: coo.longitude)
            initSearch()
        }
    }
    func backAction() {
        self.navigationController?.popViewController(animated: true)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        navbar.deleagte = self
        navbar.title = "地址选择"
        self.view.addSubview(navbar)
        
        let searchBGView = UIView()
        searchBGView.backgroundColor = UIColor.white
        self.view.addSubview(searchBGView)
        searchBGView.snp.makeConstraints { (make) in
            make.top.equalTo(navbar.snp_bottom)
            make.left.right.equalTo(0)
            make.height.equalTo(44)
        }
        let searchBr = SearchBarView.init()
        searchBGView.addSubview(searchBr)
        searchBr.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.right.equalTo(-10)
            make.centerY.equalToSuperview()
            make.height.equalTo(30)
        }
        searchV = searchBr
        searchBr.placeholderStr = "搜索地点"
        searchBr.cornerRadius = 35/2.0
        searchBr.delegate = self
        searchBr.delegateL = self
        
        AMapServices.shared().apiKey = "ca417b43e3d031db9c29382cc09a174a"
        manger.delegate = self
        manger.startUpdatingLocation()
        manger.requestAlwaysAuthorization()
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow(note:)), name:UIResponder.keyboardWillShowNotification,object: nil)
        // 监听键盘隐藏通知
        NotificationCenter.default.addObserver(self,selector: #selector(keyboardHidden(note:)),
                                               name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    var isSearchMode = false
    var reloadOnce = false
    var closeBtn:UIButton?
    //键盘弹出监听
    @objc func keyboardShow(note: Notification)  {
        guard let userInfo = note.userInfo else {return}
        guard let keyboardRect = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else{return}
        //获取动画执行的时间
        var duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        if duration == nil { duration = 0.25 }
        isSearchMode = true
        
        var btmH = 255
        if IS_IPHONE_X {
            btmH = 289
        }
        var btnH = 49
        if IS_IPHONE_X {
            btnH = 83
        }
        //获取键盘弹起的高度
        btmView.snp.updateConstraints { (make) in
            make.bottom.equalTo(-keyboardRect.height)
            make.left.right.equalTo(0)
            make.height.equalTo(btmH-btnH)
        }
        btmTitle?.isHidden = true
        btmBtn?.isHidden = true
        
        listView?.frame = btmView.bounds
        if reloadOnce == false {
            reloadOnce = true
            listView?.reloadData()
        }
        if closeBtn == nil {
            let btn = UIButton()
            btn.backgroundColor = UIColor.black
            btn.alpha = 0.4
            self.view.addSubview(btn)
            btn.addTarget(self, action: #selector(searchClose(btn:)), for: .touchUpInside)
            btn.snp.makeConstraints { (make) in
                make.top.equalTo(NavHeight + 44)
                make.left.right.equalTo(0)
                make.bottom.equalTo(btmView.snp_top)
            }
            closeBtn = btn
        }
    }
    @objc func searchClose(btn:UIButton){
        isSearchMode = false
        reloadOnce = false
        btn.removeFromSuperview()
        closeBtn = nil
        listView?.reloadData()
        IQKeyboardManager.shared.resignFirstResponder()
    }
    
    @objc func keyboardHidden(note: Notification){
        var btmH = 255
        if IS_IPHONE_X {
            btmH = 289
        }
        //        isSearchMode = false
        //获取键盘弹起的高度
        btmView.snp.updateConstraints { (make) in
            make.bottom.equalTo(0)
            make.left.right.equalTo(0)
            make.height.equalTo(btmH)
        }
        
        var btnH = 49
        if IS_IPHONE_X {
            btnH = 83
        }
        listView?.frame = CGRect(x: 0, y: 0, width: Int(ScreenWidth), height: btmH-btnH)
        
        btmTitle?.isHidden = false
        btmBtn?.isHidden = false
    }
    
    deinit {
        //记得要取消键盘通知的监听
        NotificationCenter.default.removeObserver(self)
    }
    //MARK: - 自定义delegate
    func clearSearchAction() {
        print("清楚搜索文字")
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        let request = AMapPOIKeywordsSearchRequest()
        request.keywords = searchBar.text
        request.requireExtension = true
        request.cityLimit = true
        request.requireSubPOIs = true
        search.aMapPOIKeywordsSearch(request)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("点击搜索进行--")
        searchBar.resignFirstResponder()
        
    }
    @objc func cancelKeyboard(){
        IQKeyboardManager.shared.resignFirstResponder()
    }
    @objc func backToCenter(){
        mapView.setCenter(CLLocationCoordinate2DMake(lat, lng), animated: false)
    }
    //    @objc func backAction(){
    //        self.navigationController?.popViewController(animated: true)
    //    }
    @objc func submitAction(){
        
        if adrStr != nil {
            delegate?.SJMapViewControllerSelectArd(adr: adrStr!,cityData: cityData!,loc: "\(lat)-\(lng)")
            self.navigationController?.popViewController(animated: true)
        }else{
            HUD.flash(.label("请选择地址"), delay: 1.2)
        }
    }
    //MARK: - 高德地图delegate
    
    func onPOISearchDone(_ request: AMapPOISearchBaseRequest!, response: AMapPOISearchResponse!) {
        
        if response.count == 0 {
            return
        }
        //解析response获取POI信息,具体解析见 Demo
        adrArr.removeAll()
        response.pois.forEach { (poi) in
            adrArr.append(poi)
        }
        listView?.reloadData()
    }
    
    //移动后刷新
    func mapView(_ mapView: MAMapView!, mapDidMoveByUser wasUserAction: Bool) {
        let req = AMapPOIAroundSearchRequest()
        //地址
        req.location = AMapGeoPoint.location(withLatitude: CGFloat(mapView.centerCoordinate.latitude), longitude: CGFloat(mapView.centerCoordinate.longitude))
        req.requireExtension = true
        search.aMapPOIAroundSearch(req)
        idx = IndexPath(row: 0, section: 0)
        self.listView?.scrollRectToVisible(CGRect(x: 0, y: 0, width: 1, height: 1), animated: false)
    }
    
    var annotation:MAPointAnnotation? = nil
    func mapViewRegionChanged(_ mapView: MAMapView!) {
        
        let request = AMapReGeocodeSearchRequest()
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(mapView.centerCoordinate.latitude), longitude: CGFloat(mapView.centerCoordinate.longitude))
        search.aMapReGoecodeSearch(request)
        request.requireExtension = true
        
        if annotation == nil
        {
            let pointAnnotation = MAPointAnnotation()
            annotation = pointAnnotation
            mapView.addAnnotation(annotation)
        }
        annotation!.coordinate = CLLocationCoordinate2D(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
    }
    
    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
        if annotation.isKind(of: MAPointAnnotation.self) {
            let pointReuseIndetifier = "pointReuseIndetifier"
            var annotationView: MAAnnotationView? = mapView.dequeueReusableAnnotationView(withIdentifier: pointReuseIndetifier)
            
            if annotationView == nil {
                annotationView = MAAnnotationView(annotation: annotation, reuseIdentifier: pointReuseIndetifier)
            }
            
            annotationView!.image = UIImage(named: "dingzhen")
            //设置中心点偏移,使得标注底部中间点成为经纬度对应点
            annotationView!.centerOffset = CGPoint(x: 0, y: -15);
            return annotationView!
        }
        
        return nil
    }
    
    //MARK: - cell delegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 73.5
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return adrArr.count
    }
    var idx:IndexPath? = nil
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SJMapCell") as! SJMapCell
        
        let poi = adrArr[indexPath.row]
        cell.nameLbl.text = poi.name
        cell.cityData = poi.province + "-" + poi.city + "-" + poi.district
        //1.将两个经纬度点转成投影点
        let point1 = MAMapPointForCoordinate(CLLocationCoordinate2D(latitude: lat, longitude: lng))
        let point2 = MAMapPointForCoordinate(CLLocationCoordinate2D(latitude: CLLocationDegrees(poi.location!.latitude), longitude: CLLocationDegrees(poi.location!.longitude)))
        
        //2.计算距离
        let distance = MAMetersBetweenMapPoints(point1,point2);
        
        cell.contentLbl.text = "\(Int(distance))米 | \(poi.address!)"
        cell.lat = Double(poi.location.latitude)
        cell.lng = Double(poi.location.longitude)
        cell.imgView.isHidden = true
        
        if indexPath == idx {
            if isSearchMode == false {
                cell.imgView.isHidden = false
            }
            adrStr = poi.name
            cityData = poi.province + "-" + poi.city + "-" + poi.district
        }
        
        
        return cell
    }
    var cityData:String?
    var adrStr:String?
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(indexPath.row)
        if idx == indexPath {
            if isSearchMode {
                let cell = tableView.cellForRow(at: idx!) as! SJMapCell
                mapView.setCenter(CLLocationCoordinate2D(latitude:CLLocationDegrees(cell.lat!), longitude: CLLocationDegrees(cell.lng!)), animated: false)
                adrStr = cell.nameLbl.text
                delegate?.SJMapViewControllerSelectArd(adr: cell.nameLbl.text!, cityData: cityData!, loc: "\(cell.lat!)-\(cell.lng!)")
                self.navigationController?.popViewController(animated: true)
            }
            return
        }else{
            idx = indexPath
            let cell = tableView.cellForRow(at: idx!) as! SJMapCell
            mapView.setCenter(CLLocationCoordinate2D(latitude:CLLocationDegrees(cell.lat!), longitude: CLLocationDegrees(cell.lng!)), animated: false)
            listView?.reloadData()
            adrStr = cell.nameLbl.text
            if isSearchMode {
                delegate?.SJMapViewControllerSelectArd(adr: cell.nameLbl.text!, cityData: cityData!, loc: "\(cell.lat!)-\(cell.lng!)")
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
    
    var btmTitle:UILabel?
    var btmBtn:LGButton?
    func initBtmView(view:UIView){
        let tbv = UITableView()
        tbv.separatorStyle = .none
        tbv.delegate = self
        tbv.dataSource = self
        view.addSubview(tbv)
        listView = tbv
        var btnH = 49
        if IS_IPHONE_X {
            btnH = 83
        }
        var btmH = 255
        if IS_IPHONE_X {
            btmH = 289
        }
        tbv.frame = CGRect(x: 0, y: 0, width: Int(ScreenWidth), height: btmH-btnH)
        
        listView?.register(UINib(nibName: "SJMapCell", bundle: nil), forCellReuseIdentifier: "SJMapCell")
        
        let submit_btn = LGButton()
        view.addSubview(submit_btn)
        btmBtn = submit_btn
        if isPPH {
            submit_btn.gradientStartColor = UIColor(named: "green")
            submit_btn.gradientEndColor = UIColor(named: "green")
        }else{
            submit_btn.gradientStartColor = UIColor(named: "按钮渐变色上")
            submit_btn.gradientEndColor = UIColor(named: "按钮渐变色下,字体颜色")
        }
        submit_btn.gradientHorizontal = true
        if isPPH {
            submit_btn.gradientStartColor = UIColor(named: "green")
            submit_btn.gradientEndColor = UIColor(named: "green")
        }
        submit_btn.addTarget(self, action: #selector(submitAction), for: .touchUpInside)
        submit_btn.snp.makeConstraints { (make) in
            make.bottom.left.right.equalTo(0)
            make.height.equalTo(btnH)
        }
        
        let lbl = UILabel()
        btmTitle = lbl
        view.addSubview(lbl)
        lbl.textAlignment = .center
        lbl.font = UIFont(name: "PingFangSC-Medium", size: 17)
        lbl.text = "确定"
        lbl.textColor = UIColor.white
        lbl.snp.makeConstraints { (make) in
            make.top.equalTo(tbv.snp_bottom)
            make.left.right.equalTo(0)
            make.height.equalTo(49)
        }
    }
    let locationM = AMapLocationManager()
    var btmView = UIView()
    func initMapView(lat:CLLocationDegrees,lng:CLLocationDegrees) {
        btmView.backgroundColor = UIColor.white
        self.view.addSubview(btmView)
        var btmH = 255
        if IS_IPHONE_X {
            btmH = 289
        }
        btmView.snp.makeConstraints { (make) in
            make.bottom.right.left.equalTo(0)
            make.height.equalTo(btmH)
        }
        initBtmView(view: btmView)
        
        AMapServices.shared().enableHTTPS = true
        mapView = MAMapView()
        mapView.delegate = self
        mapView.zoomLevel = 16
        mapView.isZoomEnabled = true
        mapView.setCenter(CLLocationCoordinate2D(latitude: lat, longitude: lng), animated: false)
        self.view.addSubview(mapView!)
        mapView.snp.makeConstraints { (make) in
            make.top.equalTo(NavHeight + 44)
            make.left.right.equalTo(0)
            make.bottom.equalTo(btmView.snp_top)
        }
        mapView.subviews.forEach { (item) in
            if item.isKind(of: UIImageView.classForCoder()){
                let img = item as! UIImageView
                img.image = UIImage()
            }
        }
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(cancelKeyboard))
        mapView.addGestureRecognizer(tap)
        
        let btn = UIButton()
        btn.setImage(UIImage(named: "dingwei"), for: .normal)
        btn.addTarget(self, action: #selector(backToCenter), for: .touchUpInside)
        view.addSubview(btn)
        btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(48)
            make.right.equalTo(-17.5)
            make.bottom.equalTo(btmView.snp_top).offset(-13.5)
        }
    }
    
    func initSearch() {
        search = AMapSearchAPI()
        search.delegate = self
        let request = AMapPOIAroundSearchRequest()
        //地址
        request.location = AMapGeoPoint.location(withLatitude: CGFloat(mapView.centerCoordinate.latitude), longitude: CGFloat(mapView.centerCoordinate.longitude))
        request.requireExtension = true
        search.aMapPOIAroundSearch(request)
    }
}