//
//  H5Controller.swift
//  E-Wow
//
//  Created by dong on 2021/1/6.
//

import UIKit
import WebKit

/**
 导航栏默认显示，状态栏默认深色
 */
class H5Controller: H5BaseViewController {
    private var bgColor: UIColor = UIColor(hex: "#211A2B")//.purple//.white
    private var background = "#211A2B"
    private var naviTitleIgnoreAlpha = false

    // status
    private var h5StatusBarStyle: UIStatusBarStyle = .lightContent
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupViewsByBgColor(alpha: 1)
        navigationView.backButton.isHidden = false
        
//        navigationView.backButton.setImage(R.image.nav_back(), for: .normal)
//        webView.snp.remakeConstraints { make in
//            make.top.right.left.bottom.equalTo(self.view)
//        }
//        if #available(iOS 13.0, *) {
//            h5StatusBarStyle = .darkContent
//        }else{
//        h5StatusBarStyle = .default
//        }
//        setNeedsStatusBarAppearanceUpdate()

        view.bringSubviewToFront(navigationView)

        webView.scrollView.delegate = self
    }

    private func setupViewsByBgColor(alpha: CGFloat) {
        navigationView.backgroundColor = bgColor.withAlphaComponent(alpha)
        navigationView.titleLabel.alpha = naviTitleIgnoreAlpha ? 1 : alpha
    }

    override var preferredStatusBarStyle: UIStatusBarStyle {
        return h5StatusBarStyle
    }

    override func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        super.webView(webView, didFinish: navigation)
        dlog("☁️webview didFinish: \(webView.url?.absoluteString ?? "null")")
        guard let urlPath = webView.url?.absoluteString else {
            return
        }

        adaptPageNavi(uri: urlPath, didFinish: true)
    }

    override func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        super.webView(webView, decidePolicyFor: navigationAction, decisionHandler: decisionHandler)

        guard let urlRequest = navigationAction.request.url?.absoluteString.removingPercentEncoding else {
            return
        }

        adaptPageNavi(uri: urlRequest)
    }

    private func adaptPageNavi(uri: String?, didFinish: Bool = false) {
        guard let uriStr = uri else {
            return
        }

        if uriStr.contains("activity/shoppingMall") {
            bgColor = .hexString("F04545")
            navigationView.titleLabel.textColor = .white
            naviTitleIgnoreAlpha = true
            setupViewsByBgColor(alpha: 0)
            if didFinish {
                navigationView.backButton.setImage(R.image.nav_back_white(), for: .normal)
            }
            webView.evaluateJavaScript("document.body.style.backgroundColor=\"#F04545\"") { _, _ in
            }
        }  else {
//            navigationView.backButton.setImage(R.image.nav_back(), for: .normal)
            webView.evaluateJavaScript("document.body.style.backgroundColor=\"\(background)\"") { _, _ in
            }
        }
    }

    // MARK: - override

    override func handleInit(msg: JSSDKMessage) {
        super.handleInit(msg: msg)
        if let header = msg.header {
//            if let fontColor = header.fontColor {
//                navigationView.titleLabel.textColor = UIColor.hexString(fontColor)
//                if fontColor == "#FFFFFF" {
//                    navigationView.backButton.setImage(R.image.nav_back_white(), for: .normal)
//                } else {
//                    navigationView.backButton.setImage(R.image.nav_back(), for: .normal)
//                }
//            }
            if let background = header.background {
                self.background = background
                bgColor = UIColor.hexString(background)
                setupViewsByBgColor(alpha: 1)
            }
            if header.transparent {
                setupViewsByBgColor(alpha: 0)
                webView.snp.remakeConstraints { make in
                    make.top.right.left.bottom.equalTo(self.view)
                }
                h5StatusBarStyle = .lightContent
                setNeedsStatusBarAppearanceUpdate()
            } else {
                webView.snp.remakeConstraints { make in
                    make.right.left.bottom.equalTo(self.view)
                    make.top.equalTo(navigationView.snp.bottom)
                }
                if #available(iOS 13.0, *) {
                    h5StatusBarStyle = .darkContent
                } else {
                    h5StatusBarStyle = .default
                }
                setNeedsStatusBarAppearanceUpdate()
            }
        }
    }
}

extension H5Controller: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // dlog("offset:\(scrollView.contentOffset.y)")
        if scrollView.contentOffset.y <= 60 && scrollView.contentOffset.y >= 0 {
            let aspect = scrollView.contentOffset.y / 60.0
            setupViewsByBgColor(alpha: aspect)
        } else if scrollView.contentOffset.y > 60 {
            setupViewsByBgColor(alpha: 1)
        } else {
            setupViewsByBgColor(alpha: 0)
        }
    }
}
