//
//  YHStatusAdvantageVC.swift
//  galaxy
//
//  Created by davidhuangA on 2024/7/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import WebKit
/*
 身份优势
 */

class YHStatusAdvantageVC: YHBaseViewController, WKUIDelegate, WKNavigationDelegate {
    var webview = WKWebView()
    var progBar = UIProgressView()
    
    var url = "https://cdn-public.galaxy-immi.com/app/pic/sfys.png"
    lazy var noNetWorkTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("无网络", kNotNetWorkBgName)
        view.topMargin = 222
        view.backgroundColor = .white
        view.isHidden = true
        return view
    }()
    
    lazy var bottomHoldView: YHStatusAdvantageBottomView = {
        let view = YHStatusAdvantageBottomView()
        return view
    }()
    
    lazy var viewModel: YHHomePageViewModel = {
        let vm = YHHomePageViewModel()
        return vm
    }()
    
    var isQrInfoOk: Bool = false
    
    // 是否曾今有过网络
    private var isNetWorkOkBefore: Bool = false
    
    // 当前用户是否有订单
    let serviceCenterMainReqVM: YHServiceCenterMainViewModel = YHServiceCenterMainViewModel()
    var hasOrderFlag: Bool = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    deinit {
        webview.removeObserver(self, forKeyPath: "estimatedProgress")
        NotificationCenter.default.removeObserver(self)
    }
}

// MARK: - 内部方法
private extension YHStatusAdvantageVC {
    
    // 请求订单数据
    func requestOrder() {
        if YHLoginManager.shared.isLogin()  == false {
            self.bottomHoldView.hasOrder = self.hasOrderFlag
            return
        }
        
        self.serviceCenterMainReqVM.getContactList {
            [weak self] _, _ in
            guard let self = self else { return }
            self.hasOrderFlag = self.serviceCenterMainReqVM.arrContactList.count > 0
            self.bottomHoldView.hasOrder = self.hasOrderFlag
        }
    }
    
    func loadQrInfo() {
        let params: [String: Int] = ["pid[0]": 14, "pid[1]": 16]
        viewModel.getHKEvent(param: params) { success, _ in
            if success {
                self.isQrInfoOk = true
                if let arr = self.viewModel.hkList, arr.count > 1 {
                    let item0: YHHKEventModel = arr[0]
                    if item0.list.count > 0 {
                        self.url = item0.list[0]
                        self.reloadWebUrl()
                    }
                }
            }
        }
    }
    
    func reloadWebUrl() {
        if let url = URL(string: url) {
            let request = URLRequest(url: url)
            webview.load(request)
        } else {
            let tmpUrl = YHURLEncodeHelper.urlEncodedString(url)
            if let url = URL(string: tmpUrl) {
                let request = URLRequest(url: url)
                webview.load(request)
            } else {
                printLog("url: 有问题")
            }
        }
    }
    
    func setupUI() {
        gk_navBarAlpha = 0.0
        gk_navLineHidden = false
        gk_navBackgroundColor = .white
        gk_navTitle = "身份优势"
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateNetWorkUI), name: .reachabilityChanged, object: nil)
        
        view.backgroundColor = .white
        
        requestOrder()
        
        // 获取导航栏高度
        let navHeight = self.navigationController?.navigationBar.frame.height
        // 获取状态栏高度
        let statusHeight = k_Height_StatusBar
        
        // 创建wkwebview
        webview = WKWebView(frame: CGRect(x: 0, y: statusHeight + navHeight!, width: self.view.frame.width, height: self.view.frame.height - statusHeight - navHeight! - 59 - k_Height_safeAreaInsetsBottom()))
        webview.navigationDelegate = self
        webview.scrollView.contentInsetAdjustmentBehavior = .never
        webview.scrollView.bounces = false
        webview.scrollView.delegate = self
        
        view.addSubview(webview)
        view.addSubview(bottomHoldView)
        webview.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(-20)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(bottomHoldView.snp.top).offset(-14)
        }
        
        bottomHoldView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(YHStatusAdvantageBottomView.viewH)
        }
        
        bottomHoldView.block = { tag in
            
            if tag == 0 {
                // 跳转测评页
                let vc = YHH5WebViewVC()
                vc.url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/evaluation?channel=APP-zrll"
                vc.isShowRightShareItemFlag = true
                self.navigationController?.pushViewController(vc)
            } else if tag == 1 {
                if self.isQrInfoOk {
                    if let arr = self.viewModel.hkList, arr.count > 1 {
                        let item: YHHKEventModel = arr[1]
                        if item.list.count > 1 {
                            let codeUrl =  item.list[0]// "https://public-resuorces.oss-cn-shenzhen.aliyuncs.com/app/article_clue_default_user_code1.png"
                            let downloadUrl = item.list[1]// "https://public-resuorces.oss-cn-shenzhen.aliyuncs.com/app/article_clue_default_user_code.png"
                            
                            YHConsultantQRCodeView.codeView(codeUrl, downloadUrl: downloadUrl).show()
                            
                        }
                    }
                }
            } else if tag == 2 {
                // 邀请有礼
                if YHLoginManager.shared.isLogin() {
                    let vc = YHInvitationWithGiftsViewController()
                    self.navigationController?.pushViewController(vc)
                }
            }
        }
        
        // 加载网页的进度条
        progBar = UIProgressView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 30))
        progBar.progress = 0.0
        progBar.tintColor = UIColor.brandMainColor
        webview.addSubview(progBar)
        // 监听网页加载的进度
        webview.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
        view.addSubview(noNetWorkTipsView)
        self.noNetWorkTipsView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
        }
        updateNetWorkStatusUI(needReload: false)
        
        loadQrInfo()
    }
    
//    func addRightItems() {
//        let rightButtonItem = UIBarButtonItem(image: UIImage(named: "share_item")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(share))
//        gk_navRightBarButtonItem = rightButtonItem
//        gk_navItemRightSpace = 16
//    }
    
//    @objc func share() {
//        YHShareManager.shared.shareToMiniProgram(path: "/pages/abc/d/param=https://www.baidu.com/", shareTitle: "请查看")
//    }
    
    @objc func updateNetWorkUI() {
        updateNetWorkStatusUI(needReload: true)
    }
    
    func updateNetWorkStatusUI(needReload: Bool) {
        DispatchQueue.main.async {
            if YHNetworkStatusManager.shared.isNetWorkOK {
                if needReload && self.isNetWorkOkBefore == false {
                    self.webview.stopLoading()
                    if let targetUrl = URL(string: self.url) {
                        let request = URLRequest(url: targetUrl)
                        self.webview.load(request)
                    }
                }
                self.isNetWorkOkBefore = true
            }
            
            if self.isNetWorkOkBefore == false {
                self.view.bringSubviewToFront(self.noNetWorkTipsView)
                self.noNetWorkTipsView.isHidden = YHNetworkStatusManager.shared.isNetWorkOK
            } else {
                self.noNetWorkTipsView.isHidden = true
            }
        }
    }
}

// MARK: - WKNavigationDelegate
extension YHStatusAdvantageVC {
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            self.progBar.alpha = 1.0
            progBar.setProgress(Float(webview.estimatedProgress), animated: true)
            // 进度条的值最大为1.0
            if self.webview.estimatedProgress >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseInOut, animations: { () in
                    self.progBar.alpha = 0.0
                }, completion: { (_: Bool) in
                    self.progBar.progress = 0
                })
            }
        }
    }
    
    override class func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
        
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
//        addRightItems()
    }
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        // 实现非安全链接的跳转。如果目标主视图不为空,则允许导航
        if !(navigationAction.targetFrame?.isMainFrame != nil) {
            webview.load(navigationAction.request)
        }
        return nil
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
//        // 修复弹窗弹出的问题
//        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
//        alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (_) -> Void in
//            completionHandler()
//        }))
//        self.present(alert, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        printLog("\(error.localizedDescription)")
    }
}

// MARK: - UIScrollViewDelegate
extension YHStatusAdvantageVC: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 0 {
            var alpha =  scrollView.contentOffset.y / (k_Height_NavigationtBarAndStatuBar)
            if alpha > 1.0 {
                alpha = 1.0
            }
            gk_navBarAlpha = alpha
            
        } else {
            gk_navBarAlpha = 0.0
        }
    }
}
