//
//  PQUploadViewModel.swift
//  PQSpeed
//
//  Created by SanW on 2020/8/4.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import BFCommonKit
import BFNetRequestKit
import UIKit

public class PQUploadViewModel: NSObject {
    /// 发布视频
    /// - Parameters:
    ///   - projectId 项目ID-发布创作的视频时必传，会在进入创作工具页时生成，以app_no_projectdata为前缀
    ///   - fileExtensions 视频封装格式 -必传
    ///   - title: 标题
    ///   - videoPath: 视频地址
    ///   - coverImgPath: 封面地址
    ///   - descr: 描述
    ///   - videoFromScene 视频来源场景 1：普通上传 2：创作工具，3：普通上传转创作工具，4：后台转换加工，5：卡点视频制作
    /// - Returns: <#description#>
    public class func publishVideo(projectId: String?, fileExtensions: String?, title: String, videoPath: String, coverImgPath: String?, descr: String, videoFromScene: videoFromScene, reCreateData: PQReCreateModel?, eventTrackData: PQVideoMakeEventTrackModel?, topicId: String? = nil,extParams:String? = nil, completeHander: @escaping (_ videoData: PQVideoListModel?, _ jsonDict: [String: Any]?, _ msg: String?) -> Void) {
        BFLog(message: "AKAKAAKprojectId is\(String(describing: projectId)) videoFromScene is \(videoFromScene)")
        var params: [String: Any] = ["title": title, "fileExtensions": fileExtensions ?? "application/octet-stream", "videoPath": videoPath, "descr": descr, "viewStatus": 1, "produceProjectId": (projectId ?? "") as String, "videoFromScene": videoFromScene.rawValue]
        if coverImgPath != nil, (coverImgPath?.count ?? 0) > 0 {
            params["coverImgPath"] = coverImgPath
        }
        if topicId != nil, (topicId?.count ?? 0) > 0 {
            params["topicId"] = topicId
        }
        if extParams != nil && (extParams?.count ?? 0) > 0 {
            params["reserve"] = extParams!
        }
        
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + videoSendUrl, parames: params, commonParams: commonParams()) { response, _, error, _ in
            if error != nil {
                completeHander(nil, nil, error?.msg)
                return
            }
            var jsonDict = (response as! [String: Any])
            jsonDict["title"] = title
            jsonDict["auditStatus"] = 1
            jsonDict["uid"] = BFLoginUserInfo.shared.uid
            let tempModel = PQVideoListModel(jsonDict: jsonDict)
            tempModel.uid = Int(BFLoginUserInfo.shared.uid) ?? 0
            tempModel.auditStatus = 1
            completeHander(tempModel, jsonDict, nil)
            // 发布成功
            var extParams: [String: Any] = ["source": (projectId != nil && (projectId?.count ?? 0) > 0) ? "videoCompose" : "videoUpload", "projectId": projectId ?? ""]
            if reCreateData != nil {
                extParams["projectId"] = reCreateData?.projectId ?? ""
                extParams["parentVideoId"] = reCreateData?.videoId ?? ""
                extParams["parentProjectId"] = reCreateData?.parentProjectId ?? ""
                extParams["rootProjectId"] = reCreateData?.rootProjectId ?? ""
            }
            PQEventTrackViewModel.baseReportUpload(businessType: .bt_up_process, objectType: .ot_up_publishSuccess, pageSource: nil, extParams: extParams, remindmsg: "上传相关")
            if projectId != nil {
                PQBaseViewModel.reportSendVideo(projectId!, tempModel.uniqueId ?? "", videoFromScene: videoFromScene) { isSuccess, _ in
                    if !isSuccess {
                        PQBaseViewModel.reportSendVideo(projectId!, tempModel.uniqueId ?? "", videoFromScene: videoFromScene) { isSuccess, _ in
                            if !isSuccess {
                                PQBaseViewModel.reportSendVideo(projectId!, tempModel.uniqueId ?? "", videoFromScene: videoFromScene) { isSuccess, _ in
                                    if !isSuccess {}
                                }
                            }
                        }
                    }
                }
            }
            if eventTrackData != nil {
                eventTrackData?.title = title
                eventTrackData?.videoDes = descr
                eventTrackData?.videoId = tempModel.uniqueId
                eventTrackData?.coverUrl = coverImgPath
                PQEventTrackViewModel.baseReportUpload(logType: .st_log_type_videoProduction, businessType: nil, objectType: nil, pageSource: nil, eventData: eventTrackData?.toParams(), remindmsg: "创作工具埋点上报")
            }
        }
    }

    /// 修改视频
    /// - Parameters:
    ///   - title: 标题
    ///   - videoId: 视频id
    ///   - coverImgPath: 图片地址
    ///   - descr: 描述
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func updateVideo(title: String, videoId: String, coverImgPath: String, descr: String,topicId:Int64? = nil, completeHander: @escaping (_ response:[String:Any]?,_ videoData: PQVideoListModel?, _ msg: String?) -> Void) {
        var params : Dictionary<String,Any> = ["title": title, "videoId": videoId, "coverImgPath": coverImgPath, "descr": descr, "viewStatus": 1, "barrageSwitch": 1]
        if topicId != nil && (topicId ?? 0) > 0 {
            params["topicId"] = topicId!
        }
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + updateVideoUrl, parames: params, commonParams: commonParams()) { response, _, error, _ in
            if error != nil {
                completeHander(nil,nil, error?.msg)
                return
            }
            // 1015
            let tempModel = PQVideoListModel(jsonDict: response as! [String: Any])
            tempModel.auditStatus = 1
            completeHander(response as? [String: Any],tempModel, nil)
        }
    }

    /// 获取视频封面
    /// - Parameters:
    ///   - videoId: 视频ID
    ///   - videoPath: 视频地址
    ///   - totalTime: 总时长
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func vodeoCoverImageList(videoId: String, videoPath: String, totalTime: Int, videoHeight: CGFloat, videoWidth: CGFloat, completeHander: @escaping (_ coverImages: [PQUploadModel]?, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + vodeoCoverImageUrl, parames: ["id": videoId, "videoPath": videoPath, "totalTime": totalTime], commonParams: commonParams()) { response, _, error, _ in
            if error != nil {
                completeHander(nil, error?.msg)
                return
            }
            var coverImages: [PQUploadModel] = Array<PQUploadModel>.init()
            let data: [String: Any]? = response as? [String: Any]
            if data != nil, data?.keys.contains("videoCoverImages") ?? false {
                let videoCoverImages: [String]? = data?["videoCoverImages"] as? [String]
                if videoCoverImages != nil, (videoCoverImages?.count ?? 0) > 0 {
                    for item in videoCoverImages! {
                        let tempItem = PQUploadModel()
                        tempItem.contentMode = .scaleAspectFit
                        tempItem.videoHeight = videoHeight
                        tempItem.videoWidth = videoWidth
                        tempItem.imageUrl = item
                        coverImages.append(tempItem)
                    }
                }
            }
            completeHander(coverImages, nil)
        }
    }
}
