//
//  YHLiveStateViewController.swift
//  galaxy
//
//  Created by EDY on 2024/12/2.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

enum YHLiveState: Int {
    case unknown = -1
    case start = 0
    case stop = 1
    case end = 2
    case onLive = 3
}

class YHLiveStateViewController: YHBaseViewController {
    var bgLogoImageView: UIImageView!
    var bgView: UIView!
    var blurEffect: UIBlurEffect!
    var blurView: UIVisualEffectView!
    var closeButton: UIButton!
    var shareButton: UIButton!
    var logImageView: UIImageView!
    var loginTitleLabel: UILabel!
    var loginSubTitleLabel: UILabel!
    var messageLabel: UILabel!
    var getCodeButton: UIButton!
    var state: YHLiveState = .start
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        return .portrait
    }
    private lazy var bottomView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 260))
        view.isHidden = true
        return view
    }()
    
    private lazy var recommendHeader: YHRecommendedLiveHeader = {
        let view = YHRecommendedLiveHeader(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 20))
        view.moreButtonEvent = { [weak self] in
            self?.backHomeLivePage?()
        }
        return view
    }()
    
    var shareEvent: (() -> Void)?
    var closeEvent: (() -> Void)?
    var backHomeEvent: (() -> Void)?
    var backHomeLivePage: (() -> Void)?
    private let viewModel = YHLiveSalesViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
    }
    
    func setupData(liveDetail: YHLiveDetailModel) {
        if let url = URL(string: liveDetail.avatar) {
            bgLogoImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
            logImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
        } else {
            bgLogoImageView.image = UIImage(named: "global_default_image")
            logImageView.image = UIImage(named: "global_default_image")
        }
        loginTitleLabel.text = liveDetail.account
        updateData(liveDetail)
    }
    
    func setView() {
        gk_navigationBar.isHidden = true
        view.backgroundColor = .black
        bgLogoImageView = {
            let view = UIImageView(frame: view.bounds)
            view.contentMode = .scaleAspectFill
            return view
        }()
        view.addSubview(bgLogoImageView)
        bgLogoImageView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        bgView = {
            let view = UIView(frame: view.bounds)
            view.backgroundColor = UIColor(hex: 0x000000, alpha: 0.85)
            return view
        }()
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        blurEffect = {
            return UIBlurEffect(style: .light)
        }()
        
        blurView = {
            let view = UIVisualEffectView(effect: blurEffect)
            view.frame = view.bounds
            view.alpha = 0.6
            return view
        }()
        view.addSubview(blurView)
        blurView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        closeButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "live_close"), for: .normal)
            button.addTarget(self, action: #selector(close), for: .touchUpInside)
            return button
        }()
        view.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.top.equalTo(10 + k_Height_StatusBar)
            make.width.height.equalTo(24)
        }
        
        shareButton = {
            let button = UIButton(type: .custom)
            button.setImage(UIImage(named: "live_share"), for: .normal)
            button.addTarget(self, action: #selector(share), for: .touchUpInside)
            return button
        }()
        view.addSubview(shareButton)
        shareButton.snp.makeConstraints { make in
            make.right.equalTo(-62)
            make.top.equalTo(10 + k_Height_StatusBar)
            make.width.height.equalTo(24)
        }
        
        logImageView = {
            let view = UIImageView()
            view.layer.cornerRadius = 39
            view.backgroundColor = .red
            view.clipsToBounds = true
            view.layer.borderWidth = 1
            view.layer.borderColor = UIColor.white.cgColor
            return view
        }()
        view.addSubview(logImageView)
        logImageView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(240)
            make.width.height.equalTo(78)
        }
        
        loginTitleLabel = {
            let label = UILabel()
            // label.text = "优才E老师"
            label.font = UIFont.PFSC_M(ofSize: 16)
            label.textColor = UIColor.white
            label.textAlignment = .center
            return label
        }()
        view.addSubview(loginTitleLabel)
        loginTitleLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(logImageView.snp.bottom).offset(16)
            make.height.equalTo(20)
        }
        
        let lineView = {
            let view = UIView()
            view.backgroundColor = .white.withAlphaComponent(0.24)
            return view
        }()
        view.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(loginTitleLabel.snp.bottom).offset(23)
            make.height.equalTo(0.5)
            make.width.equalTo(186)
        }
        
        loginSubTitleLabel = {
            let label = UILabel()
            label.text = "直播暂未开始"
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.white
            label.textAlignment = .center
            return label
        }()
        view.addSubview(loginSubTitleLabel)
        loginSubTitleLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(lineView.snp.bottom).offset(32)
            make.height.equalTo(20)
        }
        
        messageLabel = {
            let label = UILabel()
            label.text = "预计6月28日18:00开始～"
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.white.withAlphaComponent(0.8)
            label.textAlignment = .center
            return label
        }()
        view.addSubview(messageLabel)
        messageLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(loginSubTitleLabel.snp.bottom).offset(8)
            make.height.equalTo(20)
        }
        
        getCodeButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("返回首页", for: .normal)
            button.setTitleColor( UIColor.white, for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.layer.borderWidth = 1
            button.layer.borderColor = UIColor.white.cgColor
            button.addTarget(self, action: #selector(backHome), for: .touchUpInside)
            return button
        }()
        view.addSubview(getCodeButton)
        getCodeButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(92)
            make.top.equalTo(messageLabel.snp.bottom).offset(32)
            make.height.equalTo(40)
        }
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(lineView.snp.bottom).offset(100)
            make.height.equalTo(260)
//            make.bottom.lessThanOrEqualTo(view.safeAreaLayoutGuide.snp.bottom)//for test hjl
        }
//        bottomView.backgroundColor = .red//for test hjl
        bottomView.addSubview(recommendHeader)
        recommendHeader.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(20)
        }
    }
    
    @objc func share() {
        shareEvent?()
    }
    
    @objc func close() {
        closeEvent?()
//        dismiss(animated: true)
    }
    
    func updateData(_ liveDetail: YHLiveDetailModel) {
        let type = liveDetail.getLiveState()
        switch type {
        case .start:
            loginSubTitleLabel.text = "直播暂未开始"
            messageLabel.text = "预计\(liveDetail.start_time)开始～"
            getCodeButton.isHidden = true
            bottomView.isHidden = true
            logImageView.snp.remakeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(240)
                make.width.height.equalTo(78)
            }
        case .stop:
            loginSubTitleLabel.text = "主播离开了"
            messageLabel.text = "主播暂时离开，请稍等片刻～"
            getCodeButton.isHidden = true
            bottomView.isHidden = true
            logImageView.snp.remakeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(240)
                make.width.height.equalTo(78)
            }
        case .end:
            loginSubTitleLabel.text = "直播已结束"
            messageLabel.text = "直播已结束，去首页逛逛吧～"
            getCodeButton.isHidden = false
            getRecommendLiveList()
            case .onLive, .unknown:
            logImageView.snp.remakeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(240)
                make.width.height.equalTo(78)
            }
        }
    }
    
    @objc func backHome() {
        backHomeEvent?()
    }
    
    private func getRecommendLiveList() {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.getRecommendLiveList { [weak self] liveListInfo, _ in
            guard let self = self else {
                return
            }
            YHHUD.hide()
            guard let liveListInfo = liveListInfo, liveListInfo.live_list.count > 0 else {
                bottomView.isHidden = true
                messageLabel.isHidden = false
                getCodeButton.isHidden = false
                logImageView.snp.remakeConstraints { make in
                    make.centerX.equalToSuperview()
                    make.top.equalTo(240)
                    make.width.height.equalTo(78)
                }
                return
            }
            bottomView.isHidden = false
            messageLabel.isHidden = true
            getCodeButton.isHidden = true
            logImageView.snp.remakeConstraints { make in
                make.centerX.equalToSuperview()
                make.top.equalTo(140)
                make.width.height.equalTo(78)
            }
            bottomView.subviews.forEach { view in
                if view != self.recommendHeader {
                    view.removeFromSuperview()
                }
            }
            let arr = Array(liveListInfo.live_list.prefix(2))
            let hOffset: CGFloat = 20
            let midOffset: CGFloat = 10
            let liveWidth = (KScreenWidth - 2 * hOffset - midOffset) / 2.0
            arr.enumerated().forEach { index, model in
                if model.status == 1 {
                    let view = YHRecommendedOnLiveView()
                    view.buttonClickEvent = {
                        let playbackInfo = YHPlayerManager.PlaybackInfo(id: model.live_id, url: nil, title: model.title, roomId: nil, uid: nil, isLive: true, scene: .fullscreen)
                        YHPlayerManager.shared.enterLive(from: nil, playbackInfo: playbackInfo)
                    }
                    self.bottomView.addSubview(view)
                    view.snp.makeConstraints { make in
                        if index == 0 {
                            make.left.equalToSuperview().offset(hOffset)
                        } else {
                            make.right.equalToSuperview().offset(-hOffset)
                        }
                        make.width.height.equalTo(liveWidth)
                        make.top.equalTo(self.recommendHeader.snp.bottom).offset(16)
                        make.bottom.equalToSuperview()
                    }
                    view.updateViews(avatar: model.avatarurl, anchorName: model.account, image: model.image)
                } else if model.status == 2 {
                    let view = YHRecommendedAppointmentLiveView()
                    view.appointmentButtonEvent = { [weak self, weak view] in
                        guard let self = self else {
                            return
                        }
                        guard let view = view else {
                            return
                        }
                        self.bookLive(liveId: model.live_id, liveView: view)
                    }
                    
                    view.buttonClickEvent = { [weak self] in
                        guard let self = self else {
                            return
                        }
                        YHHUD.show(.progress(message: "加载中..."))
                        self.viewModel.getLiveStatus(liveId: model.live_id) { liveInfo, _ in
                            YHHUD.hide()
                            guard let liveInfo = liveInfo else {
                                let ctl = YHLiveAppointmentViewController(liveId: model.live_id)
                                UIViewController.current?.navigationController?.pushViewController(ctl)
                                return
                            }
                            if liveInfo.status == 2 {
                                let ctl = YHLiveAppointmentViewController(liveId: model.live_id)
                                UIViewController.current?.navigationController?.pushViewController(ctl)
                            } else {
                                let playbackInfo = YHPlayerManager.PlaybackInfo(id: model.live_id, url: nil, title: nil, roomId: nil, uid: nil, isLive: true, scene: .fullscreen)
                                YHPlayerManager.shared.enterLive(from: nil, playbackInfo: playbackInfo)
                            }
                        }
                    }
                    self.bottomView.addSubview(view)
                    view.snp.makeConstraints { make in
                        if index == 0 {
                            make.top.equalTo(self.recommendHeader.snp.bottom).offset(20)
                        } else {
                            make.top.equalTo(self.recommendHeader.snp.bottom).offset(20 + 103 + 12)
                            make.bottom.equalToSuperview()
                        }
                        make.left.right.equalToSuperview()
                        make.height.equalTo(103)
                    }
                    view.updateViews(liveTitle: model.title, fromTime: model.start_time, endTime: model.end_time, avatar: model.avatarurl, anchorName: model.account, isAppointmented: model.is_schedule_live)
                }
            }
        }
    }
    
    private func bookLive(liveId: Int, liveView: YHRecommendedAppointmentLiveView) {
        YHHUD.show(.progress(message: "加载中..."))
        viewModel.postLiveBook(id: liveId) { success, _ in
            YHHUD.hide()
            if success {
                liveView.updateAppointmentButton(isAppointmented: true)
                YHHUD.flash(message: "预约成功")
            } else {
                YHHUD.flash(message: "预约失败")
            }
        }
    }
}
