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

import UIKit

class YHlifeCollectionReusableView: UICollectionReusableView {
    static let reuseIdentifier = "YHlifeCollectionReusableView"
    var tableView: UITableView!
    var sectionView: YHlifeCollectionReusableViewHeadView!
    var dataSource: [YHLiveListModel]? {
        didSet {
            self.tableView.reloadData()
        }
    }
    private let viewModel = YHLiveSalesViewModel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }

    private func setupView() {
        sectionView = {
            let view = YHlifeCollectionReusableViewHeadView()
            view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 50)
            return view
        }()
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            tableView.contentInsetAdjustmentBehavior = .never
            tableView.backgroundColor = .white
            tableView.separatorStyle = .none
            tableView.showsHorizontalScrollIndicator = false
            tableView.showsVerticalScrollIndicator = false
            tableView.dataSource = self
            tableView.delegate = self
            tableView.tableHeaderView = sectionView
            tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01))
            tableView.register(cellWithClass: YHlifeCollectionReusableViewTableViewCell.self)
            return tableView
        }()
        addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.bottom.left.right.equalToSuperview()
        }
    }
}

extension YHlifeCollectionReusableView: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHlifeCollectionReusableViewTableViewCell.self)
        cell.dataSource = dataSource?[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 104
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }

    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard let dataSource = dataSource, dataSource.count > indexPath.row else {
            return
        }
        let model = dataSource[indexPath.row]
        YHHUD.show(.progress(message: "加载中..."))
        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)
            }
        }
        
    }
}

class YHlifeCollectionReusableViewHeadView: UIView {
    
    var flagView: UIView!
    var titleLabel: UILabel!

    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .white
        setUpView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpView() {
        backgroundColor = .white

        flagView = {
            let view = UIView()
            view.backgroundColor = UIColor.brandMainColor
            return view
        }()
        addSubview(flagView)
        flagView.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalTo(23)
            make.height.equalTo(11)
            make.width.equalTo(3)
        }
        titleLabel = {
            let label = UILabel()
            label.text = "即将开播"
            label.font = UIFont(name: "AlimamaShuHeiTi-Bold", size: 14)
            label.textColor = UIColor.mainTextColor
            return label
        }()
        addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(7)
            make.centerY.equalTo(flagView.snp.centerY)
            make.height.equalTo(17)
            make.right.equalToSuperview()
        }
    }
}

class YHlifeCollectionReusableViewTableViewCell: UITableViewCell {
    var centerImageView: UIImageView!
    var titleLabel: UILabel!
    var subTitleLabel: UILabel!
    var headImageView: UIImageView!
    var flagLabel: UILabel!
    var timelabel: UILabel!
    var actionButton: UIButton!
    var viewModel: YHLiveSalesViewModel = YHLiveSalesViewModel()

    var dataSource: YHLiveListModel? {
        didSet {
            guard let dataSource = dataSource else { return }
            self.titleLabel.text =  dataSource.title
            self.subTitleLabel.text = dataSource.account
            self.timelabel.text = dataSource.time_appointment
            flagLabel.isHidden = false
            actionButton.isSelected = dataSource.is_schedule_live
            guard let url = URL(string: dataSource.image) else { return }
            self.centerImageView.kf.setImage(with: url)
            guard let url = URL(string: dataSource.avatarurl) else { return }
            self.headImageView.kf.setImage(with: url)
        }
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        self.backgroundColor = .white
        let bgview = {
            let view = UIView()
            view.layer.borderWidth = 0.5
            view.layer.borderColor = UIColor.separatorColor.cgColor
            return view
        }()
        contentView.addSubview(bgview)
        bgview.snp.makeConstraints { make in
            make.top.equalTo(6)
            make.bottom.equalTo(-6)
            make.left.right.equalToSuperview()
        }
        
        centerImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "global_default_image")
            return imageView
        }()
        contentView.addSubview(centerImageView)
        centerImageView.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview()
            make.height.width.equalTo(92)
        }
        
        titleLabel = {
            let view = UILabel()
            view.text = "高才A香港企明星(7)"
            view.font = UIFont.PFSC_M(ofSize: 14)
            view.textColor = UIColor.mainTextColor
            view.numberOfLines = 2
            return view
        }()
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(12)
            make.right.equalToSuperview()
            make.top.equalTo(centerImageView.snp.top).offset(12)
            make.height.equalTo(22)
        }
        
        subTitleLabel = {
            let view = UILabel()
            view.text = "高才专家社"
            view.font = UIFont.PFSC_M(ofSize: 12)
            view.textColor = UIColor(hex: 0x6d788a)
            view.numberOfLines = 2
            return view
        }()
        contentView.addSubview(subTitleLabel)
        subTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(34)
            make.right.equalTo(-20)
            make.bottom.equalTo(-16.5)
            make.height.equalTo(20)
        }
        
        flagLabel = {
            let label = UILabel()
            label.text = "预告"
            label.textAlignment = .center
            label.textColor = .white
            label.backgroundColor = .brandMainColor
            label.font = UIFont.PFSC_R(ofSize: 10)
            return label
        }()
        centerImageView.addSubview(flagLabel)
        flagLabel.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.equalTo(28)
            make.height.equalTo(16)
        }
        
        timelabel = {
            let view = UILabel()
            view.text = "12月19日 09:00～11:00"
            view.font = UIFont.PFSC_M(ofSize: 12)
            view.textColor = UIColor.brandMainColor
            return view
        }()
        contentView.addSubview(timelabel)
        timelabel.snp.makeConstraints { make in
            make.left.equalTo(centerImageView.snp.right).offset(12)
            make.right.equalTo(-20)
            make.top.equalTo(centerImageView.snp.top).offset(36)
            make.height.equalTo(18)
        }
        
        headImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "global_default_image")
            imageView.layer.cornerRadius = 10
            imageView.layer.masksToBounds = true
            return imageView
        }()
        contentView.addSubview(headImageView)
        headImageView.snp.makeConstraints { make in
            make.bottom.equalTo(-15)
            make.left.equalTo(centerImageView.snp.right).offset(12)
            make.height.width.equalTo(20)
        }
        
        actionButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 12)
            button.contentHorizontalAlignment = .center
            button.setTitle("预约", for: .normal)
            button.setTitle("已预约", for: .selected)
            button.setTitleColor(UIColor(hex: 0xb3c8e9), for: .selected)
            button.setTitleColor(UIColor.brandMainColor, for: .normal)
            button.setBackgroundColor(color: UIColor(hex: 0xebf0f9), forState: .normal)
            button.addTarget(self, action: #selector(actionClick), for: .touchUpInside)
            button.layer.cornerRadius = 3
            return button
        }()
        contentView.addSubview(actionButton)
        actionButton.snp.makeConstraints { make in
            make.bottom.right.equalTo(-12)
            make.width.equalTo(60)
            make.height.equalTo(28)
        }
    }

    @objc func actionClick() {
        if YHLoginManager.shared.isLogin() == false {
            YHOneKeyLoginManager.shared.oneKeyLogin()
            return
        }
        if actionButton.isSelected {
            return
        }
        viewModel.postLiveBook(id: dataSource?.live_id ?? 0) { success, _ in
            if success {
                YHHUD.flash(message: "预约成功")
            } else {
                YHHUD.flash(message: "预约失败")
            }
        }
        actionButton.isSelected = true
    }
}
