//
//  YHHomeCollectionViewCell.swift
//  galaxy
//
//  Created by EDY on 2024/4/8.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Kingfisher
import AVFoundation
import AVKit
import Lottie

class YHHomeCollectionViewCell: UICollectionViewCell {
    static let cellReuseIdentifier = "YHHomeCollectionViewCell"
    var clickHeartEvent: (() -> Void)?
    
    lazy var viewModel: YHHomeWebViewModel = {
        let viewModel = YHHomeWebViewModel()
        return viewModel
    }()
    
    var listModel: YHHomeListModel? {
        didSet {
            updataSubViews()
        }
    }
    
    lazy var titleImageView: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: "home_banner_default_icon"))
        imageV.contentMode = .scaleAspectFill
        imageV.isUserInteractionEnabled = true
        return imageV
    }()
    
    lazy var descripeLable: UILabel = {
        let label = UILabel()
        label.text = ""
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.numberOfLines = 2
        label.lineBreakMode = .byTruncatingTail
        return label
    }()
    
    lazy var headImageView: UIImageView = {
        let imageV = UIImageView(image: UIImage(named: ""))
        imageV.contentMode = .scaleAspectFill
        return imageV
    }()
    
    lazy var heartImageViewBtn: UIButton = {
        let btn: UIButton = UIButton(type: .custom)
        btn.setImage(UIImage(named: "home_grey_heart"), for: .normal)
        btn.setImage(UIImage(named: "home_red_heart"), for: .selected)
        return btn
    }()
    
    lazy var numLable: UILabel = {
        let label = UILabel()
        label.text = ""
        label.textColor = UIColor.mainTextColor30
        label.font = UIFont.PFSC_R(ofSize: 12)
        return label
    }()
    var animationView: LottieAnimationView!

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    lazy var playButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "home_play_btn"), for: .normal)
        btn.isHidden = true
        return btn
    }()
}

extension YHHomeCollectionViewCell {
    
    @objc func clickPlayButton() {
        guard let listModel = listModel else { return }
        
        if listModel.media_url.isEmpty == false, let url = URL(string: listModel.media_url) {
            printLog(url)
            
            let vc = YHVideoPlayerVC()
            if !listModel.media_transcode_url.isEmpty {
                vc.url = listModel.media_transcode_url
            } else {
                vc.url = listModel.media_url
            }
            vc.id = listModel.id
            vc.updateBlock = {
                [weak self] item in
                guard let self = self else { return }
                self.listModel?.is_like = item.is_like
                self.listModel?.like_count = item.like_count
                
                printLog(listModel)
                self.updataSubViews()
            }
            self.parentViewController?.navigationController?.pushViewController(vc)
        }
    }
    
    private func setupUI() {
        contentView.clipsToBounds = true
        contentView.addSubview(titleImageView)
        titleImageView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(210)
        }
        
        let subHoldView = UIView()
        subHoldView.layer.backgroundColor = UIColor.white.cgColor
        subHoldView.layer.borderWidth = 0.6
        subHoldView.layer.borderColor = UIColor(red: 0.943, green: 0.952, blue: 0.969, alpha: 1).cgColor
        contentView.addSubview(subHoldView)
        subHoldView.snp.makeConstraints { make in
            make.top.equalTo(titleImageView.snp.bottom)
            make.bottom.left.right.equalToSuperview()
        }
        
        subHoldView.addSubview(descripeLable)
        descripeLable.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
        }
        
        subHoldView.addSubview(numLable)
        numLable.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-8)
            make.top.equalTo(descripeLable.snp.bottom).offset(10)
            make.height.equalTo(16)
        }
        
        animationView = {
            let view = LottieAnimationView(name: "shouye")
            view.isHidden = true
            return view
        }()
        subHoldView.addSubview(animationView)
        animationView.snp.makeConstraints { make in
            make.right.equalTo(numLable.snp.left).offset(2.5)
            make.height.width.equalTo(24)
            make.centerY.equalTo(numLable).offset(-0.5)
        }
        
        subHoldView.addSubview(heartImageViewBtn)
        heartImageViewBtn.snp.makeConstraints { make in
            make.right.equalTo(numLable.snp.left).offset(-2)
            make.height.width.equalTo(16)
            make.centerY.equalTo(numLable)
        }
        
        heartImageViewBtn.addTarget(self, action: #selector(clickHeart), for: .touchUpInside)
        heartImageViewBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
        
        contentView.addSubview(playButton)
        playButton.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.width.height.equalTo(20)
        }
        
        playButton.addTarget(self, action: #selector(clickPlayButton), for: .touchUpInside)
    }
    
    func updataSubViews() {
        guard let listModel = listModel else { return }
        titleImageView.snp.remakeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(listModel.img_height_use)
        }
        if let url = URL(string: listModel.img_url) {
            if let avifUrl = URL(string: listModel.img_url_compress) {
                titleImageView.kf.setImage(with: avifUrl, placeholder: UIImage(named: "global_default_image")) { result in
                    switch result {
                    case .success: break
                    case .failure(let error):
                        self.titleImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
                    }
                }
            } else {
                self.titleImageView.kf.setImage(with: url, placeholder: UIImage(named: "global_default_image"))
            }
        }
        descripeLable.text = listModel.title.defaultStringIfEmpty(detaultValue: "银河港生活")
        descripeLable.snp.removeConstraints()
        descripeLable.snp.remakeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.left.equalToSuperview().offset(8)
            make.right.equalToSuperview().offset(-8)
            make.height.equalTo(listModel.textH)

        }
//        DispatchQueue.main.async {
            self.numLable.text = listModel.like_count.string
            if self.animationView.isHidden {
    //            heartImageViewBtn.setImage(UIImage(named: "home_red_heart"), for: .selected)
    //            heartImageViewBtn.setImage(UIImage(named: "home_grey_heart"), for: .normal)
                
    //            heartImageViewBtn.setImage(UIImage(named: "home_grey_heart"), for: .normal)
    //            heartImageViewBtn.setImage(UIImage(named: "home_red_heart"), for: .selected)
            } else {
                self.heartImageViewBtn.setImage(UIImage(named: ""), for: .selected)
                self.heartImageViewBtn.setImage(UIImage(named: ""), for: .normal)
            }
    //        heartImageViewBtn.isSelected = listModel.is_like
            
            if listModel.is_like {
                self.heartImageViewBtn.setImage(UIImage(named: "home_red_heart"), for: .normal)
            } else {
                self.heartImageViewBtn.setImage(UIImage(named: "home_grey_heart"), for: .normal)
            }
//        }
        
        if listModel.type == 1 {
            // 视频
            playButton.isHidden = false
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapView(gestureRecognizer:)))
            contentView.addGestureRecognizer(tap)
        } else {
            // 资讯
            playButton.isHidden = true
            contentView.removeGestureRecognizers()
        }
    }
    
    @objc func clickHeart() {
        guard let listModel = listModel else { return }
        if let clickHeartEvent = clickHeartEvent {
            clickHeartEvent()
            return
        }
        
        if YHLoginManager.shared.isLogin() {
            if listModel.is_like == false {
                viewModel.getLike(listModel.id, 1) {[weak self] success, _ in
                    guard let self = self else { return }
                    if success {
                        listModel.is_like = true
                        
                        listModel.like_count += 1
                        self.numLable.text = listModel.like_count.string
                        
                        self.heartImageViewBtn.setImage(UIImage(named: ""), for: .selected)
                        self.heartImageViewBtn.setImage(UIImage(named: ""), for: .normal)
                        self.animationView.isHidden = false
                        self.animationView.loopMode = .playOnce
//                        self.updataSubViews()
                        self.animationView.play {[weak self] _ in
                            guard let self = self else { return }
                            self.animationView.isHidden = true
                            self.heartImageViewBtn.setImage(UIImage(named: "home_red_heart"), for: .normal)
                            self.updataSubViews()
                        }
                    }
                }
            } else {
                animationView.isHidden = true
                viewModel.getLike(listModel.id, 0) {[weak self] success, _ in
                    guard let self = self else { return }
                    if success {
                        listModel.is_like = false
                        listModel.like_count -= 1
                        self.updataSubViews()
                    }
                }
            }
        } else {
            YHOneKeyLoginManager.shared.oneKeyLogin()
        }
    }
    
    @objc func tapView(gestureRecognizer: UITapGestureRecognizer) {
        clickPlayButton()
    }
}
