//
//  YHVideoPlayerVC.swift
//  galaxy
//
//  Created by edy on 2024/5/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AVFoundation
import AVKit
import BMPlayer
import Kingfisher

class YHVideoPlayerVC: YHBaseViewController {

    var url:String = ""
    var id: Int = 0
    typealias Block = (YHWebModel) -> ()
    var updateBlock: Block?
    
    private var operationFlag:Bool = false
    
    lazy var viewModel: YHHomeWebViewModel = {
        return YHHomeWebViewModel()
    }()
    
    // 默认不静音
    var isVolumeDisable = getVideoPlaySilentSettings()
    
    lazy var videoControlView:YHVideoPlayerControlView = {
        let view = YHVideoPlayerControlView()
        return view
    }()
    
    lazy var player:BMPlayer = {
        // should print log, default false
        BMPlayerConf.allowLog = false
        // should auto play, default true
        BMPlayerConf.shouldAutoPlay = true
        // main tint color, default whiteColor
        BMPlayerConf.tintColor = UIColor.white
        // options to show header view (which include the back button, title and definition change button) , default .Always，options: .Always, .HorizantalOnly and .None
        BMPlayerConf.topBarShowInCase = .none
        // loader type, see detail：https://github.com/ninjaprox/NVActivityIndicatorView
        BMPlayerConf.loaderType  =  .ballRotateChase
        // enable setting the brightness by touch gesture in the player
        BMPlayerConf.enableBrightnessGestures = false
        // enable setting the volume by touch gesture in the player
        BMPlayerConf.enableVolumeGestures = false
        // enable setting the playtime by touch gesture in the player
        BMPlayerConf.enablePlaytimeGestures = true
        let player = BMPlayer(customControlView: videoControlView)
        return player
    }()
    
    lazy var shareBtn: UIButton = {
        let shareBtn = UIButton()
        shareBtn.setImage(UIImage(named: "video_share"), for: .normal)
        shareBtn.addTarget(self, action: #selector(didShareButtonClicked), for: .touchUpInside)
        shareBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 30, bottom: 20, right: 20)
        return shareBtn
    }()
    
    lazy var navBar: UIView = {
        let bar = UIView()
        let backBtn = UIButton()
        backBtn.setImage(UIImage(named: "back_icon")?.withRenderingMode(.alwaysTemplate), for: .normal)
        backBtn.tintColor = .white
        backBtn.addTarget(self, action: #selector(didBackButtonClicked), for: .touchUpInside)
        backBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 30, bottom: 20, right: 20)
        bar.addSubview(backBtn)
        bar.addSubview(self.shareBtn)
            
        backBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.left.equalTo(13)
        }
        self.shareBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.right.equalTo(-16)
        }
        return bar
    }()
    
    lazy var noNetWorkTipsView: YHEmptyDataView = {
        let view = YHEmptyDataView.createView("无网络", kNotNetWorkBgName)
        view.topMargin = 222
        view.backgroundColor = .black
        view.tipsLabel.textColor = .white
        view.isHidden = true
        return view
    }()
    
    var bottomView: YHHomeWebBottomView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createUI()
        requestData()
    }
    
    func createUI() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: YhConstant.YhNotification.didLoginSuccessNotifiction, object: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateNetWorkUI), name: .reachabilityChanged, object: nil)
        
        gk_navigationBar.isHidden = true
        self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false
        view.backgroundColor = .black
        view.addSubview(navBar)
        setupLikeAndCollectUI()
        setupPlayerUI()
        view.addSubview(self.noNetWorkTipsView)
        self.noNetWorkTipsView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_NavigationtBarAndStatuBar)
        }
        navBar.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(k_Height_statusBar())
            make.height.equalTo(k_Height_NavContentBar)
        }
        
        bottomView.snp.makeConstraints { make in
            make.bottom.left.right.equalToSuperview()
            make.height.equalTo(YHHomeWebBottomView.height + k_Height_safeAreaInsetsBottom())
        }
        updateNetWorkStatusUI(needReload: false)
    }
    
    func setupPlayerUI() {
        view.addSubview(player)
        player.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar+20)
            make.left.right.equalTo(0)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom()-YHHomeWebBottomView.height-20)
        }
        guard let videoURL = URL(string: url) else {
            YHHUD.flash(message: "无效URL")
            return
        }
        let asset = BMPlayerResource(url: videoURL)
        player.setVideo(resource: asset)
        // 默认静音
        updateVolume(isVolumeDisable)
    }
    
    func setupLikeAndCollectUI() {
        bottomView = {
            let view = YHHomeWebBottomView()
            view.tintMode = .dark
            view.isLike = false
            view.isStar = false
            view.likeBlock = { [weak self] flag in
                guard let self = self else { return }
                if YHLoginManager.shared.isLogin() == false {
                    self.player.pause()
                    YHOneKeyLoginManager.shared.oneKeyLogin()
                    return
                }
                if flag {
                    self.viewModel.getLike(self.id, 1) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                } else {
                    self.viewModel.getLike(self.id, 0) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                }
            }
            
            view.starBlock = { [weak self] flag in
                guard let self = self else { return }
                if YHLoginManager.shared.isLogin() == false {
                    self.player.pause()
                    YHOneKeyLoginManager.shared.oneKeyLogin()
                    return
                }
                if flag {
                    self.viewModel.getStar(self.id, 1) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            YHHUD.flash(message: "已加入收藏")
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                } else {
                    self.viewModel.getStar(self.id, 0) {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            operationFlag = true
                            self.getData()
                        } else {
                            operationFlag = false
                        }
                    }
                }
            }
            return view
        }()
        view.addSubview(bottomView)
    }
    
    // 静音更新
    func updateVolume(_ disable:Bool) {
        videoControlView.isSilient = disable
        player.avPlayer?.isMuted = disable
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension YHVideoPlayerVC {
    @objc func didBackButtonClicked() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func didShareButtonClicked() {
        shareVideoContent()
    }
}

extension YHVideoPlayerVC {
    
    func getData() {
        if id > 0 {
            viewModel.getWebDetail(self.id) {[weak self] success, error in
                guard let self = self else { return }
                if success {
                    guard let model = self.viewModel.mainModel else { return }
                    bottomView.likeCount = model.like_count
                    bottomView.starCount = model.collect_count
                    bottomView.isStar = model.is_collect
                    bottomView.isLike = model.is_like
                    
                    if operationFlag {
                        self.updateBlock?(model)
                    }
                }
            }
        }
    }
    
    func requestData() {
        if id == 0 {
            if self.url.contains("?id=") {
                let list = self.url.components(separatedBy: "?id=")
                if list.count == 2 {
                    if let iddd = list[1].int {
                        id = iddd
                        getData()
                        return
                    }
                }
            }
        }
        getData()
    }
    
    func shareVideoContent() {
        
        if YHLoginManager.shared.isLogin() == false {
            self.player.pause()
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        
        let title: String = self.viewModel.mainModel?.title ?? ""
        let link:String = self.viewModel.mainModel?.media_url ?? ""
        let thumbUrl = self.viewModel.mainModel?.img_url ?? ""
        if thumbUrl.isEmpty {
            YHHUD.flash(message:"分享失败")
            return
        }
        if link.isEmpty {
            YHHUD.flash(message:"分享失败")
            return
        }
        
        requestThumbImage(url: thumbUrl) { thumbImg in
            guard let thumbImg = thumbImg else {
                DispatchQueue.main.async {
                    YHHUD.flash(message:"分享失败")
                }
                return
            }
            self.player.pause()
            YHShareManager.shared.sendVideoContent(title, "", thumbImg, link:link)
        }
    }
    
    func requestThumbImage(url: String, block:((UIImage?)->())?) {
        let url = URL(string: url) // 替换为你要下载的图片 URL
        let downloader = KingfisherManager.shared.downloader
        downloader.downloadImage(with: url!) { result in
            switch result {
            case .success(let value):
                let image = value.image
                // 在这里使用下载得到的 image 对象
                block?(image)
            case .failure(let error):
                // 下载失败，处理错误
                print("图片下载失败: \(error)")
                block?(nil)
            }
        }
    }
    
    @objc func loginSuccess() {
        printLog("登录成功，进行相应的 UI刷新操作")
        requestData()
    }
    
    @objc func updateNetWorkUI() {
        
        if YHNetworkStatusManager.shared.isNetWorkOK {
            if self.noNetWorkTipsView.isHidden == false {
                self.noNetWorkTipsView.isHidden = true
                self.requestData()
                if let videoURL = URL(string: self.url) {
                    self.player.pause()
                    let asset = BMPlayerResource(url: videoURL)
                    self.player.setVideo(resource: asset)
                    self.player.play()
                }
            }
        }
        self.shareBtn.isHidden = !YHNetworkStatusManager.shared.isNetWorkOK
    }
    
    func updateNetWorkStatusUI(needReload:Bool) {
        DispatchQueue.main.async {
            self.noNetWorkTipsView.isHidden = YHNetworkStatusManager.shared.isNetWorkOK
            self.shareBtn.isHidden = !YHNetworkStatusManager.shared.isNetWorkOK
            self.view.bringSubviewToFront(self.noNetWorkTipsView)
            
        }
    }
}
