//
//  MPPositive_MoreOperationTableViewCell.swift
//  MusicPlayer
//
//  Created by Mr.Zhou on 2024/5/29.
//

import UIKit
import DownloadButton
class MPPositive_MoreOperationDownLoadTableViewCell: UITableViewCell {
    //设置下载按钮
    lazy var loadBtn:PKDownloadButton = {
        let btn:PKDownloadButton = .init()
        btn.isUserInteractionEnabled = false
        //开始下载状态
        btn.startDownloadButton.cleanDefaultAppearance()
        btn.startDownloadButton.setBackgroundImage(UIImage(named: "Song_Unload'logo"), for: .normal)
        //下载结束状态
        btn.downloadedButton.setBackgroundImage(UIImage(named: "Song_Loaded'logo"), for: .normal)
        btn.downloadedButton.isUserInteractionEnabled = false
        btn.downloadedButton.setAttributedTitle(nil, for: .normal)
        //停止下载状态
        btn.stopDownloadButton.stopButton.setImage(UIImage(named: "download"), for: .normal)
        btn.stopDownloadButton.isUserInteractionEnabled = false
        btn.stopDownloadButton.tintColor = UIColor(hex: "#80F988")
        btn.stopDownloadButton.stopButtonWidth = 2
        btn.stopDownloadButton.filledLineWidth = 3*width
        btn.stopDownloadButton.filledLineStyleOuter = true
        
        //加载状态设置
        btn.pendingView.tintColor = UIColor(hex: "#80F988")
        btn.pendingView.radius = 12*width
        btn.pendingView.emptyLineRadians = 2*width
        btn.pendingView.spinTime = 3
        return btn
    }()
    var song:MPPositive_SongItemModel!{
        didSet{
            setProgress(song.videoId)
        }
    }
    private lazy var titleLabel:UILabel = createLabel("Status" ,font: .systemFont(ofSize: 14*width, weight: .regular), textColor: .white, textAlignment: .left)
    //根据输入videoId检索是否下载
    func setProgress(_ videoId:String) {
        guard videoId.isEmpty == false, videoId == song?.videoId else {
            return
        }
        MP_DownloadManager.shared.loadQueue.async {
            [weak self] in
            guard let self = self else {return}
            MP_DownloadManager.shared.isDownloadedFileDocuments(videoId) { statu in
                if statu == false {
                    //未下载,判断是否加入了下载队列
                    if MP_DownloadManager.shared.isTasksQueue(for: videoId) {
                        //加入下载队列，确定是否活跃下载队列中
                        if MP_DownloadManager.shared.isActiveTask(for: videoId) {
                            DispatchQueue.main.async {
                                self.loadBtn.state = .downloading
                                self.titleLabel.text = "Downloading"
                            }
                            //活跃中，获取下载值
                            if let progress = MP_DownloadManager.shared.getProgress(for: videoId) {
                                //下载中
                                DispatchQueue.main.async {
                                    self.loadBtn.stopDownloadButton.progress = progress
                                }
                            }
                        }else {
                            //处于队列中，还未开始下载
                            DispatchQueue.main.async {
                                //未加入下载队列
                                self.loadBtn.state = .pending
                                self.titleLabel.text = "Downloading"
                            }
                        }
                    }else {
                        DispatchQueue.main.async {
                            //未加入下载队列
                            self.loadBtn.state = .startDownload
                            self.titleLabel.text = "Download"
                        }
                    }
                }else {
                    DispatchQueue.main.async {
                        //已经完成下载
                        self.loadBtn.state = .downloaded
                        self.titleLabel.text = "Remove download"
                    }
                }
            }
        }
    }
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        backgroundColor = .clear
        //注册通知
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(downloadProgressAction(_ :)), notificationName: .download_progress_source)
        NotificationCenter.notificationKey.add(observer: self, selector: #selector(downloadEndAction(_ :)), notificationName: .dowload_end_source)
        configure()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    //收到progress加载
    @objc private func downloadProgressAction(_ sender:Notification) {
        if let dict = sender.object as? [String:String], let videoId = dict["videoId"], let currentVideoId = song?.videoId, videoId == currentVideoId {
            //比较当前videoId
            setProgress(videoId)
        }
    }
    //收到下载结束
    @objc private func downloadEndAction(_ sender:Notification) {
        if let dict = sender.object as? [String:String], let videoId = dict["videoId"], let currentVideoId = song?.videoId, videoId == currentVideoId {
            setProgress(videoId)
        }
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    private func configure() {
        contentView.addSubview(loadBtn)
        loadBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24*width)
            make.top.equalToSuperview().offset(12*width).priority(999)
            make.bottom.equalToSuperview().offset(-12*width)
            make.left.equalToSuperview().offset(18*width)
        }
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(loadBtn.snp.right).offset(12*width)
        }
    }
}
