//
//  YHVODPlayerViewController.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/25.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import AgoraRtcKit
import UIKit

class YHVODPlayerViewController: YHBasePlayerViewController {
    // MARK: - Properties

    private let vodId: Int
    var startPosition: Int = 0
    private let viewModel = YHLiveSalesViewModel()
    private var goodsListView: YHLiveShopView?

    private lazy var progressControl: YHVideoProgressControl = {
        let view = YHVideoProgressControl()
        return view
    }()
    
    private lazy var bottomImageView: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "live_player_bg"))
        return imageView
    }()
    
    private lazy var centerPlayIcon: UIImageView = {
        let imageView = UIImageView(image: UIImage(named: "live_center_play"))
        imageView.isHidden = true
        return imageView
    }()
    
    private var isFirstAppear = true

    // MARK: - Initialization

    init(id: Int, url: String? = nil, title: String? = nil) {
        vodId = id
        super.init(nibName: nil, bundle: nil)
        player?.delegate = self
        currentPlayingURL = url
        currentVideoTitle = title
        if let url = url {
            play(url: url, title: title)
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func play(url: String, title: String? = nil) {
        currentPlayingURL = url
        currentVideoTitle = title
        YHPlayerManager.shared.play(url: url, inView: playerView, title: title, isLive: false)
    }

    // MARK: - Lifecycle

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupGestures()
        loadVideoDetail()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if !isFirstAppear {
            if player?.getPlayState() != .paused {
                if let url = playbackInfo?.url {
                    play(url: url, title: playbackInfo?.title)
                    player?.seek(to: startPosition)
                    player?.resume()
                    DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
                        self.progressControl.setPlaying(self.player?.getPlayState() == .playing)
                        self.centerPlayIcon.isHidden = self.player?.getPlayState() == .playing
                    })
                }
            } else {
                player?.resume()
            }
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if let player = player {
            startPosition = player.getPosition()
        }
        player?.pause()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if isFirstAppear {
            isFirstAppear = false
        }
    }

    // MARK: - SetupView

    private func setupUI() {
        playerView.addSubview(bottomImageView)
        bottomImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        containerView.addSubview(progressControl)
        containerView.addSubview(centerPlayIcon)
        containerView.bringSubviewToFront(centerPlayIcon)
        progressControl.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-102)
        }
        centerPlayIcon.snp.makeConstraints { make in
            make.centerY.centerX.equalToSuperview()
            make.height.width.equalTo(62)
        }

        topBarView.closeButtonClickEvent = { [weak self] in
            self?.closeLive()
        }

        topBarView.zoomButtonClickEvent = { [weak self] in
            YHAnalytics.track("APP_RecordedPage_ClickWindowPlay")
            self?.enterFloating()
        }

        topBarView.shareButtonClickEvent = { [weak self] in
            YHAnalytics.track("APP_RecordedPage_ClickShare")
            self?.shareLive()
        }
        // 现在改为全部
        let needHideZoom = true //playbackInfo?.needHideZoomButton == true
        topBarView.hideZoomButton(needHideZoom)
        progressControl.setPlaying(player?.getPlayState() == .playing)
        centerPlayIcon.isHidden = player?.getPlayState() == .playing
    }
    
    private func setupGestures() {
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        playerView.addGestureRecognizer(tap)
    }
    
    @objc private func handleTap() {
        let isPlaying = player?.getPlayState() == .playing
        if isPlaying {
            player?.pause()
        } else {
            player?.resume()
        }
    }

    private func enterFloating() {
        guard let playbackInfo = playbackInfo else {
            return
        }
        YHPlayerManager.shared.enterFloating(from: self, playbackInfo: playbackInfo)
    }

    private func closeLive() {
        YHPlayerManager.shared.stop(type: .main)
        if let nav = navigationController, nav.viewControllers.count > 1 {
            nav.popViewController(animated: true)
        } else {
            dismiss(animated: true)
        }
    }

    private func shareLive() {
        guard let recordedDetailModel = viewModel.recordedDetailModel else {
            return
        }
        YHShareAlertView.show(image: recordedDetailModel.recorded_image, title: "@" + recordedDetailModel.account, subMessage: recordedDetailModel.recorded_title, linkUrl: recordedDetailModel.recorded_h5_url, isLive: false, fromAiSale: true)
    }

    // MARK: - Data Loading

    private func loadVideoDetail() {
        viewModel.getRecordedDetail(id: vodId) { [weak self] recordedDetail, error in
            guard let self = self else { return }

            if let recordedDetail = recordedDetail {
                self.handleVideoDetailSuccess(recordedDetail)
            } else {
                printLog("YHVODPlayerViewController: 请求失败")
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }

    private func handleVideoDetailSuccess(_ detail: YHRecordedDetailModel) {
        // 更新顶部栏信息
        topBarView.setupTopBarView(
            headUrl: detail.avatar,
            nickname: detail.account,
            count: detail.access_num
        )
        // 如果没有预设URL，使用接口返回的URL播放
        if currentPlayingURL == nil, detail.recorded_url.count > 0 {
            playbackInfo?.url = detail.recorded_url
            playbackInfo?.title = detail.recorded_title
            play(url: detail.recorded_url, title: detail.recorded_title)
        }
        progressControl.configure(with: detail.recordedVideoSlice.compactMap {
            $0.tag
        })
        progressControl.onPlayStatusChanged = { [weak self] isPlaying in
            printLog("播放状态：\(isPlaying)")
            if isPlaying {
                self?.player?.resume()
            } else {
                self?.player?.pause()
            }
        }
        // 选择片段回调
        progressControl.onSegmentSelected = { [weak self] index in
            printLog("选择片段：\(index)")
            guard detail.recordedVideoSlice.count > index else {
                return
            }
            let item = detail.recordedVideoSlice[index]
            self?.player?.seek(to: item.start_second * 1000 + 1)
        }
        // 时间改变回调
        progressControl.onTimeChanged = { [weak self] time in
            printLog("跳转到：\(time)秒")
            self?.player?.seek(to: Int(time * 1000.0))
        }

        progressControl.updateGiftCount(detail.goods.count)
        progressControl.giftButtonClickEvent = { [weak self] in
            YHAnalytics.track("APP_RecordedPage_ClickProductWindow")
            self?.showGoods()
        }
        if let player = player {
            let duration = player.getDuration()
            let position = player.getPosition()
            updateProgressControl(player, position: position)
            if duration > 0 {
                updateProgressMarks(with: duration)
            }
        }
    }

    private func showGoods() {
        let list = viewModel.recordedDetailModel?.goods ?? []
        let view = YHLiveShopView.show { [weak self] index in
            guard list.count > index else {
                return
            }
            let model = list[index]
            self?.gotoH5GoodsDetail(id: model.id)
        }
        view.fromPage = .vod
        view.dataSource = list
        view.closeEvent = { [weak self] in
            self?.goodsListView = nil
        }
        view.buyData = { [weak self] index in
            guard list.count > index else {
                return
            }
            let model = list[index]
            self?.createOrder(id: model.id)
        }
        goodsListView = view
    }

    private func createOrder(id: Int) {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.createOrder(source: 2, sourceId: vodId, productId: id) { [weak self] orderModel, error in
            YHHUD.hide()
            guard let self = self else {
                return
            }
            guard let orderModel = orderModel else {
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                return
            }
            var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/order/order-confirm" + "?id=\(orderModel.id)"
            if YHLoginManager.shared.isLogin() {
                let token = YHLoginManager.shared.h5Token
                let urlHasParam = String.hasQueryParameters(urlString: url)
                if urlHasParam {
                    url = url + "&param=" + token
                } else {
                    url = url + "?param=" + token
                }
            }
            var tUrl = url
            if !url.contains("navigationH=") {
                tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                if url.contains("?") {
                    tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
                }
            }
            let vc = YHH5WebViewVC()
            vc.url = tUrl
            vc.isHideNavigationBar = false
            vc.isFullScreenFlag = false
            goodsListView?.dismiss()
            navigationController?.pushViewController(vc)
        }
    }

    private func gotoH5GoodsDetail(id: Int) {
        var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/goods/sales-detail" + "?id=\(id)"
        if YHLoginManager.shared.isLogin() {
            let token = YHLoginManager.shared.h5Token
            let urlHasParam = String.hasQueryParameters(urlString: url)
            if urlHasParam {
                url = url + "&param=" + token
            } else {
                url = url + "?param=" + token
            }
        }
        var tUrl = url
        if !url.contains("navigationH=") {
            tUrl = url + "?navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            if url.contains("?") {
                tUrl = url + "&navigationH=\(k_Height_NavigationtBarAndStatuBar)"
            }
        }
        let vc = YHH5WebViewVC()
        vc.url = tUrl
        vc.isHideNavigationBar = false
        goodsListView?.dismiss()
        navigationController?.pushViewController(vc)
    }
}

// MARK: - YHPlayerDelegate

extension YHVODPlayerViewController: YHPlayerDelegate {
    func player(_ player: YHPlayer, didChangedTo positionMs: Int, atTimestamp timestampMs: TimeInterval) {
        DispatchQueue.main.async {
            self.updateProgressControl(player, position: positionMs)
            printLog("####$$$didChangedTo positionMs: \(positionMs)")
        }
    }

    func player(_ player: YHPlayer, didChangedToState state: AgoraMediaPlayerState, reason: AgoraMediaPlayerReason) {
        DispatchQueue.main.async {
            switch state {
            case .opening:
                printLog("####$$$.opening: \(player.getDuration())")
            case .openCompleted:
                let duration = player.getDuration()
                let position = player.getPosition()
                self.updateProgressControl(player, position: position)
                self.updateProgressMarks(with: duration)
                
                printLog("####$$$.openCompleted: \(player.getDuration())")
            case .playing:
                self.progressControl.setPlaying(true)
                printLog("####$$$.playing: \(player.getDuration())")
                self.centerPlayIcon.isHidden = true
            case .paused, .stopped:
                printLog("####$$$.paused, .stopped")
                self.progressControl.setPlaying(false)
                self.centerPlayIcon.isHidden = false
            case .failed:
                //self.showAlert(message: "播放失败，错误原因：\(reason.rawValue)")
                self.centerPlayIcon.isHidden = false
            default:
                break
            }
        }
    }

    func player(_ player: YHPlayer, didChangedToPosition position: Int) {
        DispatchQueue.main.async {
            self.updateProgressControl(player, position: position)
        }
    }

    func player(_ player: YHPlayer, didReceiveVideoSize size: CGSize) {
        // 处理视频尺寸变化，如有需要
        DispatchQueue.main.async {
            //
        }
    }
    
    private func updateProgressMarks(with duration: Int) {
        if let recordedVideoSlice = self.viewModel.recordedDetailModel?.recordedVideoSlice, recordedVideoSlice.count > 0 {
            var marks: [Double] = []
            recordedVideoSlice.forEach { item in
                marks.append(Double(item.start_second * 1000) / Double(duration))
            }
            self.progressControl.setupMarkers(marks: marks)
        }
    }

    private func updateProgressControl(_ player: YHPlayer, position: Int) {
        let duration = player.getDuration()
        guard duration > 0 else { return }
        var currentIndex: Int?
        if let recordedVideoSlice = viewModel.recordedDetailModel?.recordedVideoSlice, recordedVideoSlice.count > 0 {
            currentIndex = recordedVideoSlice.firstIndex(where: { item in
                return (position >= item.start_second * 1000) && (position <= item.end_second * 1000)
            })
//            let lastIndex = recordedVideoSlice.count - 1
//            recordedVideoSlice.enumerated().forEach { index, item in
//                if position >= item.start_second * 1000, position <= item.end_second * 1000 {
//                    currentIndex = index
//                    return
//                } else if index == lastIndex, position >= item.end_second * 1000 {
//                    currentIndex = index
//                    return
//                } else if position > item.end_second * 1000, index + 1 < lastIndex {
//                    let next = recordedVideoSlice[index + 1]
//                    if position < next.start_second * 1000 {
//                        currentIndex = index
//                        return
//                    }
//                } else if position <= recordedVideoSlice[0].start_second * 1000 {
//                    currentIndex = 0
//                    return
//                }
//            }
        }
        progressControl.updateTime(Double(position) / 1000.0, duration: Double(duration) / 1000.0, currentIndex: currentIndex)
    }
}
