//
//  PQStuckPointViewModel.swift
//  PQSpeed
//
//  Created by SanW on 2021/4/28.
//  Copyright © 2021 BytesFlow. All rights reserved.
//

import BFAnalyzeKit
import BFCommonKit
import BFMediaKit
import BFNetRequestKit
import BFUIKit
import UIKit

public class PQStuckPointViewModel: NSObject {
    /// 获取卡点音乐分类列表
    /// - Parameters:
    /// 通过 parentTagId 来区分层级，第一级会带上 '热门' 标签音乐列表，获取第二级标签列表会带上所选第二级的 '全部' 标签音乐列表
    ///   - parentTagId: 标签父级 ID（默认 0 第一层）
    ///   - pageSize: 音乐列表每页个数（默认 20）
    ///   - complateHandle: <#complateHandle description#>
    class func stuckPointMusicCategoryList(parentTagId: Int64 = 0, pageSize _: Int = 20, complateHandle: @escaping (_ categoryList: [PQStuckPointMusicTagsModel], _ msg: String?, _ tagAttributes: ([UICollectionViewLayoutAttributes], CGFloat)?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + stuckPointMusicCategoryUrl, parames: ["parentTagId": parentTagId], commonParams: commonParams()) { response, _, error, _ in
            var tagsList = Array<PQStuckPointMusicTagsModel>.init()
            if response is NSNull || response == nil {
                complateHandle(tagsList, error?.msg, nil)
                return
            }
            let tagsTempArr = response as? [[String: Any]]
            if tagsTempArr != nil, (tagsTempArr?.count ?? 0) > 0 {
                for dict in tagsTempArr! {
                    let tempMusic = PQStuckPointMusicTagsModel(jsonDict: dict)
                    tempMusic.parentTagId = parentTagId
                    tagsList.append(tempMusic)
                }
            }
            tagsList.first?.isSelected = true
            complateHandle(tagsList, nil, (parentTagId != 0) ? PQStuckPointViewModel.dealWithAttributesWithTags(tagsList: tagsList) : nil)
        }
    }

    /// 计算标签frame
    /// - Parameter tagsList: <#tagsList description#>
    /// - Returns: <#description#>
    class func dealWithAttributesWithTags(tagsList: [PQStuckPointMusicTagsModel]) -> ([UICollectionViewLayoutAttributes], CGFloat) {
        var attributesArray = [UICollectionViewLayoutAttributes]()
        // 遍历数据计算每个item的属性并布局
        let lineSpace: CGFloat = 8
        let itemSpace: CGFloat = 8
        var currtentX: CGFloat = 0
        var currtentY: CGFloat = 0
        let itemHeight: CGFloat = cDefaultMargin * 3
        let maxWidth: CGFloat = cScreenWidth - cDefaultMargin * 12 - 32
        for (index, data) in tagsList.enumerated() {
            let indexPath = IndexPath(item: index, section: 0)
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            var width: CGFloat = sizeWithText(text: "  \(data.tagName ?? "")  ", font: UIFont.systemFont(ofSize: 12), size: CGSize(width: maxWidth, height: itemHeight)).width
            if width > maxWidth {
                width = maxWidth
            }
            if (currtentX + width + itemSpace) > maxWidth {
                currtentY = currtentY + lineSpace + itemHeight
                currtentX = 0
            }
            attributes.frame = CGRect(x: currtentX, y: currtentY, width: width, height: itemHeight)
            currtentX = currtentX + itemSpace + width
            attributesArray.append(attributes)
        }
        return (attributesArray, attributesArray.count > 0 ? currtentY + lineSpace + itemHeight : 0)
    }

    /// 卡点音乐某个分类下列表
    /// - Parameters:
    ///   - tagId: 标签 ID
    ///   - parentTagId: 标签父级 ID
    ///   - pageNum: 音乐列表页码（默认 1）
    ///   - pageSize: 音乐列表每页个数（默认 20）
    ///   - videoCount: 选择视频素材个数
    ///   - imageCount: 选择图片素材个数
    ///   - totalDuration: 选择素材总时长
    ///   - complateHandle: <#complateHandle description#>
    /// - Returns: <#description#>
    class func stuckPointMusicPageList(tagId: Int64, parentTagId: Int64 = 0, pageNum: Int = 1, pageSize: Int = 20, videoCount: Int = 0, imageCount: Int = 0, totalDuration: Float64 = 0, oldDataMusic: [PQVoiceModel]? = nil, complateHandle: @escaping (_ musicPageList: [PQVoiceModel], _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + stuckPointMusicPageUrl, parames: ["tagId": tagId, "parentTagId": parentTagId, "pageNum": pageNum, "pageSize": pageSize], commonParams: commonParams()) { response, _, error, _ in
            var musicPageList = Array<PQVoiceModel>.init()
            if response is NSNull || response == nil {
                complateHandle(musicPageList, error?.msg)
                return
            }
            let tempArr = response as? [[String: Any]]
            if tempArr != nil, (tempArr?.count ?? 0) > 0 {
                for (_, dict) in tempArr!.enumerated() {
                    let tempMusic = PQVoiceModel(jsonDict: dict)
                    tempMusic.cacheTagID = tagId
                    if tempMusic.rhythmSdata.count > 0 && (videoCount > 0 || imageCount > 0 || totalDuration > 0) {
//                        tempMusic.endTime = tempMusic.startTime + tempMusic.stuckPointCuttingTime(videoCount: videoCount, imageCount: imageCount, totalDuration: totalDuration)
                        BFLog(message: "music:\(tempMusic.musicName ?? ""),\(tempMusic.startTime),\(tempMusic.endTime)")
                    }
                    if tempMusic.endTime <= tempMusic.startTime {
                        tempMusic.endTime = tempMusic.startTime + 40
                    }

                    let haveIndex = oldDataMusic?.firstIndex(where: { (music) -> Bool in
                        music.musicId == tempMusic.musicId
                    })
                    if haveIndex == nil {
                        musicPageList.append(tempMusic)
                    }
                }
            }
            complateHandle(musicPageList, nil)
        }
    }

    /// 获取某个音乐的卡点数据
    /// - Parameters:
    ///   - musicId: <#musicId description#>
    ///   - originType:音乐来源：1 上传 2 爬取
    ///   - complateHandle: <#complateHandle description#>
    /// - Returns: description
    class func stuckPointMusicDetailData(musicId: String, originType: Int, complateHandle: @escaping (_ musicDetaiData: PQVoiceModel?, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + stuckPointMusicDetailUrl, parames: ["musicId": musicId, "originType": originType], commonParams: commonParams()) { response, _, error, _ in
            if response is NSNull || response == nil {
                complateHandle(nil, error?.msg)
                return
            }
            let tempDict = (response as? [String: Any])
            if tempDict != nil, (tempDict?.keys.count ?? 0) > 0 {
                complateHandle(PQVoiceModel(jsonDict: tempDict!), nil)
            } else {
                complateHandle(nil, nil)
            }
        }
    }

    /// 请求再创作项目信息
    /// - Parameter projectId: 项目id
    /// - Returns: <#description#>
    public class func stuckPointProjectMusicInfo(projectId: String, complateHandle: @escaping (_ musicDetaiData: PQVoiceModel?, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + stuckPointProjectMusicInfoUrl, parames: ["projectId": projectId], commonParams: commonParams()) { response, _, error, _ in
            if response is NSNull || response == nil {
                complateHandle(nil, error?.msg)
                return
            }
            let tempDict = (response as? [String: Any])
            if tempDict != nil, tempDict?.keys.contains("rhythmMusicData") ?? false {
                let musicData: PQVoiceModel = PQVoiceModel(jsonDict: tempDict?["rhythmMusicData"] as? [String: Any] ?? [:])
                if tempDict?.keys.contains("rhythmMusicIn") ?? false {
                    musicData.rhythmMusicIn = (Float64("\(tempDict?["rhythmMusicIn"] ?? "0")") ?? 0) / 1_000_000
                }
                if tempDict?.keys.contains("rhythmMusicOut") ?? false {
                    musicData.rhythmMusicOut = (Float64("\(tempDict?["rhythmMusicOut"] ?? "0")") ?? 0) / 1_000_000
                }
                if tempDict?.keys.contains("rhythmMusicSpeed") ?? false, "\(tempDict?["rhythmMusicSpeed"] ?? "")" != "<null>" {
                    musicData.speed = Int("\(tempDict?["rhythmMusicSpeed"] ?? "2")") ?? 2
                }
                musicData.originProjectId = projectId
                complateHandle(musicData, nil)
            } else {
                complateHandle(nil, nil)
            }
        }
    }
}
