//
//  QSLSearchFriendVC.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/10/23.
//

import UIKit
import MAMapKit
import Kingfisher
import AMapSearchKit

class QSLSearchFriendVC: QSLBaseController {
    var searchPhone = ""
    var isMove = false
    var isLoading = false
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setUI()
    }
    
    func setUI(){
        
        setUpMap()

        if(QSLConfig.phoneLocationEnable && searchPhone.count > 0){
            startLoading()
            QSLNetwork().request(.userPhoneAttribution(dict: ["phoneNumber":searchPhone])) { response in
                let model = response.mapObject(QSLConfModel.self, modelKey: "data")
                if(model.location.count > 0){
                    var currentSearchKey = model.location
                    
                    if(model.location.contains("市") && model.location.contains("省")){
                        let pattern = "省(.+?市)"
                        if let regex = try? NSRegularExpression(pattern: pattern),
                           let match = regex.firstMatch(in: currentSearchKey, range: NSRange(currentSearchKey.startIndex..., in: currentSearchKey)),
                           let range = Range(match.range(at: 1), in: currentSearchKey) {
                            currentSearchKey = String(currentSearchKey[range])
                        }
                        
                    }
                    self.requestAmapLocation(currentSearchKey)
                    return
                }
                
                self.startLocalMapAnimation()
                
            } fail: { code, msg in
                self.startLocalMapAnimation()
            }
        } else{
            startLocalMapAnimation()
        }
    }
    
    func requestAmapLocation(_ str : String){
        let req = AMapDistrictSearchRequest.init()
        req.keywords = str
        req.requireExtension = true
        self.mapSearch.aMapDistrictSearch(req)
    }
    
    func startLocalMapAnimation(){
        let randomCityCoordinate: (city: String, province: String, latitude: Double, longitude: Double) = [
            ("北京市", "北京市", 39.90403, 116.40753),
            ("上海市", "上海市", 31.23037, 121.47370),
            ("广州市", "广东省", 23.12908, 113.26436),
            ("武汉市", "湖北省", 30.59276, 114.30525),
            ("成都市", "四川省", 30.65984, 104.06304),
            ("西安市", "陕西省", 34.34127, 108.93984),
            ("沈阳市", "辽宁省", 41.80570, 123.43147),
            ("南京市", "江苏省", 32.05838, 118.79647),
            ("郑州市", "河南省", 34.74661, 113.62533),
            ("乌鲁木齐市", "新疆维吾尔自治区", 43.82559, 87.61688)
        ].randomElement()!
        
        
        startMapAnimation(longitude: randomCityCoordinate.longitude, latitude: randomCityCoordinate.latitude ,isShowLocation: false)
        
        startLoading()
        
    }
    
    func startLoading(){
        if(!isLoading){
            let bgView = UIView.init(frame: CGRect.init(x: 0, y: 0, width: QSLConst.qsl_kScreenW, height: QSLConst.qsl_kScreenH))
            self.view.addSubview(bgView)
            bgView.backgroundColor = UIColor.init(white: 0, alpha: 0.45)
            
            self.loadingView = QSLLoadingView(frame: CGRect(x: 0, y: 0, width: 170.rpx, height: 170.rpx))
            self.loadingView.center = view.center
            self.view.addSubview(self.loadingView)
            self.loadingView.completion = {
                print("加载完成")
            }
            self.loadingView.progress = 0 // 设置进度

            // 模拟进度更新
            Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { timer in
                self.loadingView.progress += 1
                if self.loadingView.progress >= 100 {
                    timer.invalidate()
                }
            }
            
            isLoading = true
        }
    }
    
    
    func startMapAnimation(longitude:Double, latitude:Double, isShowLocation:Bool = false){
        isMove = true
        
        roadMapView.setZoomLevel(4, animated: true)

        roadMapView.setCenter(CLLocationCoordinate2D(latitude: latitude, longitude: longitude), animated: true)
        
        var firstZoom : CGFloat = 5
        if(isShowLocation){
            firstZoom = 5
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            self.roadMapView.setZoomLevel(firstZoom, animated: true)
            let randomProgress1 = CGFloat.random(in: 20...35)
            if self.loadingView.progress < randomProgress1 {
                self.loadingView.progress = randomProgress1
            }
        }

        var secondZoom : CGFloat = 6
        if(isShowLocation){
            secondZoom = 6.5
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            self.roadMapView.setZoomLevel(secondZoom, animated: true)
            let randomProgress2 = CGFloat.random(in: 45...75)
            if self.loadingView.progress < randomProgress2 {
                self.loadingView.progress = randomProgress2
            }
        }

        var thirdZoom : CGFloat = 7
        if(isShowLocation){
            thirdZoom = 8
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.roadMapView.setZoomLevel(thirdZoom, animated: true)
            let randomProgress3 = CGFloat.random(in: 90...100)
            if self.loadingView.progress < randomProgress3 {
                self.loadingView.progress = randomProgress3
            }
        }

        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
            self.navigationController?.popViewController(animated: false)
            QSLJumpManager.shared.pushToVip(type: QSLVipJumpType.add)
        }
    }
    
    // 初始化高德地图设置
    func setUpMap() {
        AMapServices.shared().enableHTTPS = true
        self.initView()
    }
    
    // 高德地图
    lazy var roadMapView = {
        
        let _mapView = MAMapView()
        _mapView.delegate = self
        
        _mapView.showsUserLocation = false
        _mapView.isUserInteractionEnabled = false
        _mapView.zoomLevel = 3;
        
        _mapView.isShowsBuildings = false
        _mapView.showsCompass = false
        _mapView.showsScale = false
        _mapView.isRotateCameraEnabled = false
        
        _mapView.mapType = .satellite
        //高德地图用的坐标帮我生成10个 分别是中国10个不同省份的省的市中心坐标
        return _mapView
    }()
    
    lazy var mapSearch: AMapSearchAPI = {
        let item = AMapSearchAPI.init()
        item?.delegate = self
        return item!
    }()
    
    lazy var loadingView: QSLLoadingView = {
        let item = QSLLoadingView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        return item
    }()

}

// MARK: - 设置地图相关方法
extension QSLSearchFriendVC:MAMapViewDelegate {
    
    func mapView(_ mapView: MAMapView!, viewFor annotation: (any MAAnnotation)!) -> MAAnnotationView! {
        
        if annotation is MAPointAnnotation {
            
            let reuseIdentifier = "pointReuseIdentifier"
            
            // 尝试从缓存池中重用AnnotationView
            var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? QSLHomeAnnotatinView
            if annotationView == nil {
                annotationView = QSLHomeAnnotatinView(annotation: annotation, reuseIdentifier: reuseIdentifier)
                annotationView?.title = annotation.title
            }
            
            // 设置AnnotationView属性
            annotationView?.isEnabled = false
            annotationView?.image = UIImage(named: annotation.subtitle ?? "")
            
            annotationView?.canShowCallout = false
            
            // 设置偏移量
            annotationView?.centerOffset = CGPoint(x: 0, y: -18)
            annotationView?.calloutOffset = CGPoint(x: 0, y: -5)
            
            // 判断标题是否是“终点”，决定是否选中
            annotationView?.isSelected = true
            
            return annotationView
        }
        return nil
    }
    
    func mapView(_ mapView: MAMapView!, didSingleTappedAt coordinate: CLLocationCoordinate2D) {
        
    }
    
}

extension QSLSearchFriendVC : AMapSearchDelegate{
    func onDistrictSearchDone(_ request: AMapDistrictSearchRequest!, response: AMapDistrictSearchResponse!) {
        if(!isMove){
            if(response.districts.count > 0){
                let dist : AMapDistrict = response.districts[0] 
                startMapAnimation(longitude: dist.center.longitude, latitude: dist.center.latitude)
                
            }else{
                startLocalMapAnimation()
            }
        }
    }
    
    func aMapSearchRequest(_ request: Any!, didFailWithError error: (any Error)!) {
        if(!isMove){
            startLocalMapAnimation()
        }
    }
}

extension QSLSearchFriendVC {
    
    func initView() {
        
        self.view.addSubview(roadMapView)
        roadMapView.snp.makeConstraints { make in
            make.top.right.left.equalTo(0)
            make.edges.equalToSuperview()
        }

    }
}

