//
//  PQBaseViewModel.swift
//  PQSpeed
//
//  Created by SanW on 2020/5/25.
//  Copyright © 2020 BytesFlow. All rights reserved.
//

import Alamofire
import UIKit
import ObjectMapper
import RealmSwift
import BFCommonKit
import BFNetRequestKit

public class PQBaseViewModel: NSObject {
    
   public typealias completeHander = (_ userInfo: [String: Any]?, _ msg: String?) -> Void
    
    /// 搜索背景音乐
    /// - Parameters:
    ///   - keyWord: 搜索key
    ///   - pageNum: 当前页
    ///   - pageSize: 每页个数 默认 :30
    ///   - videoCount: 卡点音乐数据搜索-视频素材个数
    ///   - imageCount: 卡点音乐数据搜索-图片素材个数
    ///   - totalDuration: 卡点音乐数据搜索-素材总时长
    ///   - completeHander: completeHander description
    /// - Returns: <#description#>
    public class func searchBGMListData(_ keyWord: String?, _ pageNum: Int = 1, _ pageSize: Int = 30,videoCount: Int = 0, imageCount: Int = 0, totalDuration: Float64 = 0, completeHander: @escaping (_ bgmList: [PQVoiceModel], _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.materialSearchApi + searchBGMMaterialUrl, parames: ["keyWord": keyWord ?? "", "pageNo": pageNum, "pageSize": pageSize], commonParams: commonParams(), encoding: JSONEncoding.default, isJsonEncodingNormal: true) { response, _, error, _ in
            DispatchQueue.global().async {
                var bgmList = Array<PQVoiceModel>.init()
                if response is NSNull || response == nil {
                    DispatchQueue.main.async {
                        completeHander(bgmList, error?.msg)
                    }
                    return
                }
                let tempArr = (response as? [String: Any])?["entityList"] as? [[String: Any]]
                if tempArr != nil {
                    for item in tempArr! {
                        let tempModel = PQVoiceModel(jsonDict: item)
                        tempModel.volume = 30
                        tempModel.voiceType = VOICETYPT.BGM.rawValue
                        if tempModel.rhythmSdata.count > 0 && (videoCount > 0 || imageCount > 0 ||  totalDuration > 0)  {
//                            tempModel.endTime = tempModel.startTime + tempModel.stuckPointCuttingTime(videoCount: videoCount, imageCount: imageCount, totalDuration: totalDuration)
                        }
                        bgmList.append(tempModel)
                    }
                }
                DispatchQueue.main.async {
                    completeHander(bgmList, nil)
                }
            }
        }
    }
    /// 请求系统配置
    /// - Parameter completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func systemConfig(completeHander: @escaping (_ isSuccess: Bool) -> Void) {
        if PQSingletoMemoryUtil.shared.isFinishedCoging {
            completeHander(true)
            return
        }
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + systemAppConfigUrl, parames: nil, commonParams: commonParams()) { response, _, _, _ in
            if response != nil, !(response is NSNull), (response as! [String: Any]).keys.contains("needLogin") {
                let needLogin: String = "\((response as! [String: Any])["needLogin"] ?? "0")"
                saveUserDefaults(key: cNeedLoginKey, value: needLogin)
                PQSingletoMemoryUtil.shared.needLogin = needLogin == "1"
                PQSingletoMemoryUtil.shared.isFinishedCoging = true
                completeHander(true)
            } else {
                completeHander(false)
            }
        }
    }

    /// 系统设置
    /// - Parameter completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func systemBaseConfig(completeHander: @escaping (_ isSuccess: Bool) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + systemConfigUrl, parames: nil, commonParams: commonParams()) { _, _, _, _ in
            completeHander(true)
        }
    }
  
 

    /// 删除某个视频
    /// - Parameters:
    ///   - videoId: <#videoId description#>
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func deleteVideo(videoId: Int, completeHander: @escaping (_ isSuccess: Bool,_ videoId: Int, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + deleteVideoUrl, parames: ["videoId": videoId], commonParams: commonParams()) { response, _, error, _ in
            if response != nil {
                postNotification(name: cDeleteVideoSuccessKey, userInfo: ["videoId": "\(videoId)"])
                completeHander(true,videoId, nil)
            } else {
                completeHander(false,videoId,error?.msg)
            }
        }
    }

    /// 不感兴趣某个视频b
    /// - Parameters:
    ///   - videoId: 视频Id
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func hateVideo(videoId: Int, completeHander: @escaping (_ isSuccess: Bool, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + hateVideoUrl, parames: ["videoId": videoId], commonParams: commonParams()) { response, _, error, _ in
            if response != nil {
                completeHander(true, nil)
            } else {
                completeHander(false, error?.msg)
            }
        }
    }

    /// 获取用户发布最新/最热视频
    /// - Parameters:
    ///   - type: 1-最新列表 2-最热列表
    ///   - targetUid: 目标用户
    ///   - pageSize: 页面大小
    ///   - pageNo: 当前页
    ///   - currentVideoId: 当前视频ID
    ///   - sortField: 排序方式 1：时间，2：热度
    ///   - layoutType: 页面排版方式 1：单列，2：双列
    ///   - lastTimestamp: 最后一条记录的时间戳
    /// - Returns: <#description#>
    public class func userInfoVideoList(type: Int = 1, targetUid: Int, pageSize: Int = 10, pageNo: Int, currentVideoId _: Int = 0, sortField _: Int = 1, layoutType _: Int = 2, lastTimestamp: Int, completeHander: @escaping (_ listData: [PQVideoListModel]?, _ videoList: [[PQVideoListModel]]?, _ msg: String?) -> Void) {
        var url: String = PQENVUtil.shared.longvideoapi
        if type == 1 {
            url = url + latelyByCollectionIdUrl
        } else {
            url = url + hotByCollectionIdUrl
        }
        var params: [String: Any] = ["targetUid": targetUid, "pageSize": pageSize, "sortField": type]
        if type == 1 {
            params["lastTimestamp"] = lastTimestamp
        } else {
            params["pageNo"] = pageNo
        }
        BFNetRequestAdaptor.postRequestData(url: url, parames: params, commonParams: commonParams()) { response, _, error, _ in
            BFLog(message: "当前线程:\(Thread.isMainThread) ")
            DispatchQueue.global().async {
                BFLog(message: "当前线程 global:\(Thread.isMainThread) ")
                var listData = Array<PQVideoListModel>.init()
                var videoList = Array<[PQVideoListModel]>.init()

                if !(response is NSNull), response != nil {
                    let tempArr = response as! [[String: Any]]
                    for item in tempArr {
                        let tempModel = PQVideoListModel(jsonDict: item)
                        if targetUid == Int(BFLoginUserInfo.shared.uid) {
                            tempModel.pageSource = .sp_videoDetail_upload
                        } else {
                            tempModel.pageSource = .sp_videoDetail_userHomePage
                        }
                        listData.append(tempModel)
                        if tempModel.auditStatus == 5, tempModel.transcodeStatus == 3 {
                            videoList.append([tempModel])
                        }
                    }
                    DispatchQueue.main.async {
                        BFLog(message: "当前线程 main:\(Thread.isMainThread) ")
                        completeHander(listData, videoList, nil)
                    }
                } else {
                    DispatchQueue.main.async {
                        BFLog(message: "当前线程main:\(Thread.isMainThread) ")
                        completeHander(listData, videoList, error?.msg)
                    }
                }
            }
        }
    }

    /// 请求举报原因列表
    /// - Parameters:
    ///   - isReportUser: 是否举报用户
    ///   - groupId: 组id
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func reportList(isReportUser: Bool, groupId _: String?, completeHander: @escaping (_ listData: [PQBaseModel]?) -> Void) {
        var url: String = PQENVUtil.shared.longvideoapi
        if isReportUser {
            url = url + reportUserListUrl
        } else {
            url = url + reportVideoListUrl
        }
        BFNetRequestAdaptor.postRequestData(url: url, parames: nil, commonParams: commonParams()) { response, _, _, _ in
            var reportList = Array<PQBaseModel>.init()
            if response is NSNull || response == nil {
                completeHander(reportList)
                return
            }
            if isReportUser {
                for item in response as! [String] {
                    let tempModel = PQBaseModel()
                    tempModel.title = item
                    reportList.append(tempModel)
                }
            } else {
                let tempArr = response as! [[String: Any]]
                for item in tempArr {
                    let reasonsArr = item["reasons"] as! [String]
                    for reasonsItem in reasonsArr {
                        let tempModel = PQBaseModel()
                        tempModel.title = reasonsItem
                        reportList.append(tempModel)
                    }
                }
            }
            completeHander(reportList)
        }
    }

    /// 举报视频/用户
    /// - Parameters:
    ///   - isReportUser: 是否是举报用户
    ///   - videoId: 视频ID
    ///   - reason: 举报原因
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func reportOprate(isReportUser: Bool, uniqueId: Int, reason: String?, completeHander: @escaping (_ isSuccess: Bool) -> Void) {
        var params: [String: Any] = ["reason": reason ?? ""]
        var url: String = PQENVUtil.shared.longvideoapi
        if isReportUser {
            url = url + reportUserUrl
            params["reportUid"] = uniqueId
        } else {
            url = url + reportVideoUrl
            params["videoId"] = uniqueId
        }
        BFNetRequestAdaptor.postRequestData(url: url, parames: params, commonParams: commonParams()) { _, _, _, _ in
            completeHander(true)
        }
    }

    /// 拉黑/移除某个用户
    /// - Parameters:
    ///   - targetUid: <#targetUid description#>
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func bannedUser(isBanned: Bool, targetUid: Int, completeHander: @escaping (_ isSuccess: Bool, _ isBanned: Bool) -> Void) {
        var url: String = PQENVUtil.shared.longvideoapi
        if isBanned {
            url = url + bannedUserUrl
        } else {
            url = url + unBannedUserUrl
        }
        BFNetRequestAdaptor.postRequestData(url: url, parames: ["targetUid": targetUid], commonParams: commonParams()) { _, _, _, _ in
            postNotification(name: cBannedNotiKey, userInfo: ["userId": targetUid, "isBanned": isBanned ? 1 : 0])
            completeHander(true, isBanned)
        }
    }

    /// 某个用户是否被拉黑
    /// - Parameters:
    ///   - targetUid: <#targetUid description#>
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func isBannedUser(targetUid: Int, completeHander: @escaping (_ isSuccess: Bool, _ isBanned: Bool) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + isBannedUserUrl, parames: ["targetUid": targetUid], commonParams: commonParams()) { response, _, _, _ in
            if response == nil {
                completeHander(false, false)
            } else {
                completeHander(true, (response as! Int) == 1)
            }
        }
    }

    /// 获取用户管理列表
    /// - Parameter completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    class public func bannedUserList(completeHander: @escaping (_ listData: [PQUserInfoModel]?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + bannedUserListUrl, parames: nil, commonParams: commonParams()) { response, _, _, _ in
            var listData = Array<PQUserInfoModel>.init()
            if response is NSNull || response == nil {
                completeHander(listData)
                return
            }
            let responseArr: [[String: Any]] = response as! [[String: Any]]
            for dictItem in responseArr {
                let tempModel = PQUserInfoModel(jsonDict: dictItem)
                tempModel.isBanned = true
                listData.append(tempModel)
            }
            completeHander(listData)
        }
    }

    /// 获取视频详情数据
    /// - Parameters:
    ///   - isBatch: 是否批量获取
    ///   - videoId: 视频id ,isBatch = true 时，用英文,隔开
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func videoDetailInfo(isBatch: Bool = false, videoId: String, completeHander: @escaping (_ videoDatas: [[PQVideoListModel]]?, _ code: Int?, _ mag: String?) -> Void) {
        var url: String = PQENVUtil.shared.longvideoapi
        var params: [String: Any] = [:]

        if isBatch {
            url = url + videosDetailUrl
            params = ["videoIds": videoId]
        } else {
            url = url + videoDetailUrl
            params = ["videoId": videoId]
        }
        BFNetRequestAdaptor.postRequestData(url: url, parames: params, commonParams: commonParams()) { response, _, error, _ in
            if response is NSNull || response == nil {
                completeHander(nil, error?.code, error?.msg)
                return
            }
            var videoDatasList = Array<[PQVideoListModel]>.init()
            if !isBatch {
                let tempModel = PQVideoListModel(jsonDict: response as! [String: Any])
                videoDatasList.append([tempModel])
            } else {
                if response is [[String: Any]] {
                    let tempArr = response as! [[String: Any]]
                    for item in tempArr {
                        let tempModel = PQVideoListModel(jsonDict: item)
                        tempModel.tab_pageType = .TAB_PAGETYPE_RECOMM
                        tempModel.pageSource = .sp_category
                        videoDatasList.append([tempModel])
                    }
                }
            }
            completeHander(videoDatasList, 0, nil)
        }
    }

    public class func h5ShareLinkInfo(videoId: String, pageSource: PAGESOURCE, completeHander: @escaping (_ shareLinkPath: String?, _ mag: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + h5ShareLinkUrl, parames: ["videoId": videoId, "pageSource": pageSource.rawValue, "h5WxRootPageSource": pageSource.rawValue], commonParams: commonParams()) { response, _, _, _ in
            if response is NSNull || response == nil {
                completeHander(nil, "获取分享地址失败")
                return
            }
            completeHander(response as? String, nil)
        }
    }

    public class func wxFriendShareInfo(videoId: String, completeHander: @escaping (_ shareImagePath: String?, _ shareTitle: String?, _ shareWeappRawId: String?, _ mag: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + wxFriendUrl, parames: ["videoId": videoId], commonParams: commonParams()) { response, _, _, _ in
            if response is NSNull || response == nil {
                completeHander(nil, nil, nil, "获取分享好友数据失败")
                return
            }
            let responseDic = response as! [String: String]
            completeHander(responseDic["shareImgPath"], responseDic["shareTitle"], responseDic["shareWeappRawId"], nil)
        }
    }

    /// 获取白名单设置
    /// - Returns: <#description#>
    public class func datashowAllowData(completeHander: @escaping (_ isShowInfo: Bool, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + datashowAllowUrl, parames: ["mid": getMachineCode()], commonParams: commonParams(), encoding: JSONEncoding.default, isJsonEncodingNormal: true) { response, _, _, _ in
            if response is NSNull || response == nil {
                completeHander(false, "获取白名单数据失败")
                return
            }
            completeHander((response as? Int) == 1, nil)
        }
    }
    
    
    /// add by ak 取 STS token
    /// - Parameter completeHander: completeHander description
    public class func getStsToken(completeHander: @escaping completeHander) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + getStsTokenUrl, parames: ["fileType": "2", "type": 1], commonParams: commonParams()) { response, _, error, _ in
            if error != nil {
                completeHander(nil, error?.msg)
                return
            }
            completeHander(response as? [String: Any], nil)
        }
    }
    
    /// 获取OSS
    /// - Parameter completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func ossTempToken(completeHander: @escaping completeHander) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + ossTempTokenUrl, parames: ["type": "2", "fileType": "1"], commonParams: commonParams()) { response, _, _, _ in
            completeHander(response as? [String: Any], nil)
        }
    }
    
    /// 请求APP 常规配置参数
    /// - Parameter completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func getBaseConfig(completeHander: @escaping (_ titles: Array<String>?) -> Void) {
      
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.longvideoapi + getBaseConfigURL, parames: nil, commonParams: commonParams()) { response, _, _, _ in
            if response != nil, !(response is NSNull) {
 
                let responseDic = response as! [String: Any]
                BFLog(message: "推荐的标题为\(String(describing: responseDic["rhythmVideoTitles"]))")
                completeHander(responseDic["rhythmVideoTitles"] as? Array<String>)
            } else {
                completeHander(nil)
            }
        }
    }

}

// MARK: - 草稿箱相关

/// 草稿箱相关
extension PQBaseViewModel {
    /// 保存草稿-进入创作工具调用
    /// - Parameters:
    ///   - draftboxId: 草稿ID
    ///   - title: 草稿标题
    ///   - coverUrl: 封面url
    ///   - sdata: 结构化数据
    ///   - videoFromScene:上传场景 1：普通上传 2：创作工具，3：普通上传转创作工具，4：后台转换加工，5：卡点视频制作
    ///   - copyType:卡点视频制作再创作传 - 传3
    ///   - originProjectId:卡点视频制作再创作传-源项目ID从那个项目做同款
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func saveDraftbox(draftboxId: String?, title: String?, coverUrl: String?, sdata: String, videoFromScene: videoFromScene,copyType:Int? = nil,originProjectId:String? = nil, completeHander: @escaping (_ draftboxInfo: [String: Any]?, _ msg: String?) -> Void) {
        var parames: [String: Any] = ["sdata": sdata, "fromScene": videoFromScene.rawValue]
        if draftboxId != nil {
            parames["draftboxId"] = draftboxId
        }
        if copyType != nil && videoFromScene == .stuckPoint{
            parames["copyType"] = 3
        }
        if originProjectId != nil && videoFromScene == .stuckPoint{
            parames["originProjectId"] = originProjectId
        }
        if title != nil {
            parames["title"] = title
        }
        if coverUrl != nil {
            parames["coverUrl"] = coverUrl
        }
        BFLog(message: "保存草稿参数为：\(parames) \n\n sdata is:\n \(sdata) \n")
        /* 返回数据格式
         "coverUrl": "string",
         "dataVersionCode": 0,
         "draftboxId": "string",
         "duration": 0,
         "projectId": "string",
         "title": "string",
         "updateTimestamp": 0
         */
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + saveDraftboxUrl, parames: parames, commonParams: commonParams()) { response, _, error, _ in
            if error != nil {
                completeHander(nil, error?.msg)
                return
            }
            BFLog(message: "保存草稿返回数据 ：\(String(describing: response)))")
            completeHander(response as? [String: Any], nil)
        }
    }

    /// 保存项目-合成的视频上传完成后发布视频send之前调用
    /// - Parameters:
    ///   - projectId: <#projectId description#>
    ///   - ossObjectKey: <#ossObjectKey description#>
    ///   - draftboxId: <#draftboxId description#>
    ///   - videoId: <#videoId description#>
    ///   - sdata: <#sdata description#>
    ///   - videoFromScene:上传场景 1：普通上传 2：创作工具，3：普通上传转创作工具，4：后台转换加工，5：卡点视频制作
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func saveProject(draftboxId: String?, sdata: String, videoFromScene: videoFromScene, rhythmMode:createStickersModel? = nil, completeHander: @escaping (_ projectId: String?, _ msg: String?) -> Void) {
        var parames: [String: Any] = ["sdata": sdata,"fromScene": videoFromScene.rawValue]
        if draftboxId != nil {
            parames["draftboxId"] = draftboxId
        }
        if rhythmMode != nil {
            parames["rhythmMode"] = rhythmMode!.rawValue
        }
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + saveProjectUrl, parames: parames, commonParams: commonParams()) { response, _, error, _ in
            if error != nil {
                completeHander(nil, error?.msg)
                return
            }
            BFLog(message: "生成的项目id ：\(String(describing: response))")
            completeHander(response as? String, nil)
        }
    }

    /// 更新项目
    /// - Parameter projectId: 项目 ID
    /// - Parameter produceStatus: 合成状态 必传-合成状态（5：合成成功，99：合成失败）
    /// - Parameter completeHander: 回调
    public class func updateProject(projectId: String?, produceStatus: String, completeHander: @escaping (_ projectId: String?, _ msg: String?) -> Void) {
        var parames: [String: String] = ["produceStatus": produceStatus]

        if projectId != nil {
            parames["projectId"] = projectId
        }
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + updateProjectUrl, parames: parames, commonParams: commonParams()) { response, _, error, _ in
            if error != nil {
                completeHander(nil, error?.msg)
                return
            }
            BFLog(message: "生成的项目id ：\(String(describing: response))")
            completeHander(response as? String, nil)
        }
    }

    /// 发布视频后上报
    /// - Parameters:
    ///   - projectId: 项目ID
    ///   - videoId: 视频ID
    ///   - videoFromScene:上传场景 1：普通上传 2：创作工具，3：普通上传转创作工具，4：后台转换加工，5：卡点视频制作
    ///   - completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func reportSendVideo(_ projectId: String, _ videoId: String, videoFromScene: videoFromScene, completeHander: @escaping (_ isSeccess: Bool, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + reportSendVideoUrl, parames: ["projectId": projectId, "videoId": videoId, "fromScene": videoFromScene.rawValue], commonParams: commonParams()) { _, _, error, _ in

            BFLog(message: "发布视频后上报:projectId = \(projectId),videoId = \(videoId)")
            if error != nil {
                completeHander(false, error?.msg)
                return
            }
            completeHander(true, nil)
        }
    }

    /// 获取用户项目草稿箱数据
    /// - Parameters:
    ///   - lastTimestamp: 最后一条时间戳
    ///   - pageSize: 每页大小
    ///   - isSelected: 是否已选
    ///   - completeHander: <#completeHander description#>
    public class func listUserDraftbox(lastTimestamp: Int, pageSize: Int = 10, isSelected: Bool = false, completeHander: @escaping (_ projectList: [PQEditProjectModel]?, _ msg: String?) -> Void) {
        let params: [String: Any] = ["pageSize": pageSize, "lastTimestamp": lastTimestamp]
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + listUserDraftboxUrl, parames: params, commonParams: commonParams()) { response, _, error, _ in
            if error?.code == -1009 || error?.code == -1001 {
                cShowHUB(superView: nil, msg: "网络不可用")
            }
            if response is NSNull || response == nil {
                completeHander(nil, error?.msg)
                return
            }
            var projectList = Array<PQEditProjectModel>.init()
            let tempList = (response as? [[String: Any]])
            if tempList != nil, (tempList?.count ?? 0) > 0 {
                let draftDB: Realm = PQSingletoRealmUtil.shared.getDraftDB(uid: BFLoginUserInfo.shared.uid)
                for item in tempList! {
                    let tempModel: PQEditProjectModel? = Mapper<PQEditProjectModel>().map(JSON: item)
                    tempModel?.isSelected = isSelected
                    if tempModel != nil {
                        let localData = PQSingletoRealmUtil.shared.reamlQueryObjects(realm: draftDB, PQEditProjectModel.self, filter: "draftboxId == '\(tempModel?.draftboxId ?? "")'")
                        if localData != nil, (localData?.count ?? 0) > 0 {
                            tempModel?.cacheDataVersionCode = (localData?.first as? PQEditProjectModel)?.dataVersionCode ?? 0
                        }
                        projectList.append(tempModel!)
                    }
                }
            }
            completeHander(projectList, "请求成功")
        }
    }

    /// 获取草稿箱数量
    /// - Parameter completeHander: <#completeHander description#>
    /// - Returns: <#description#>
    public class func draftboxUserCount(completeHander: @escaping (_ draftboxCount: Int, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + draftboxUserCountUrl, parames: nil, commonParams: commonParams()) { response, _, error, _ in
            if response is NSNull || response == nil {
                completeHander(0, error?.msg)
                return
            }
            completeHander((response as? Int) ?? 0, nil)
        }
    }

    /// 删除草稿箱
    /// - Parameters:
    ///   - isBatch: 是否批量删除（多个用英文逗号分隔）
    ///   - draftboxIds: 草稿id
    ///   - completeHander: <#completeHander description#>
    public class func deleteDraftbox(isBatch: Bool = false, draftboxIds: String?, completeHander: @escaping (_ isSuccess: Bool, _ msg: String?) -> Void) {
        var url: String = PQENVUtil.shared.clipapiapi
        var params: [String: Any] = Dictionary<String, Any>.init()
        if isBatch {
            url = url + deleteMultiDraftboxUrl
            params["draftboxIds"] = draftboxIds ?? ""
        } else {
            url = url + deleteDraftboxUrl
            params["draftboxId"] = draftboxIds ?? ""
        }
        BFNetRequestAdaptor.postRequestData(url: url, parames: params, commonParams: commonParams()) { _, _, error, _ in
            completeHander(error == nil, error?.msg)
        }
    }

    /// 复制草稿箱
    /// - Parameters:
    ///   - draftboxId: 草稿箱id
    ///   - title: 草稿箱标题
    ///   - copyType: 复制类型（1：复制自己的项目，2：创建副本(复制别人的项目) 3:再创作）
    ///   - completeHander: <#completeHander description#>
    public class func copyDraftbox(draftboxId: String?, title: String, copyType: Int, completeHander: @escaping (_ newDraftboxId: String?, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + copyDraftboxUrl, parames: ["draftboxId": draftboxId ?? "", "title": title, "copyType": copyType], commonParams: commonParams()) { response, _, error, _ in
            if response is NSNull || response == nil {
                completeHander(nil, error?.msg)
                return
            }
            completeHander(response as? String, nil)
        }
    }

    /// 更新草稿名称
    /// - Parameters:
    ///   - draftboxId: 草稿id
    ///   - title: 标题
    ///   - completeHander: <#completeHander description#>
    public class func updateDraftBoxTitle(draftboxId: String?, title: String, completeHander: @escaping (_ newDraftData: PQEditProjectModel?, _ msg: String?) -> Void) {
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + updateDraftboxTitleUrl, parames: ["draftboxId": draftboxId ?? "", "title": title], commonParams: commonParams()) { response, _, error, _ in
            if response is NSNull || response == nil {
                completeHander(nil, error?.msg)
                return
            }
            completeHander(Mapper<PQEditProjectModel>().map(JSON: response as! [String: Any]), nil)
        }
    }

    /// 获取草稿箱结构化数据
    /// - Parameters:
    ///   - : <# description#>
    ///   - completeHander: <#completeHander description#>
    public class func draftboxGetSdata(draftboxId: String?, completeHander: @escaping (_ projectModel: PQEditSdataModel?, _ msg: String?) -> Void) {
        let params: [String: Any] = ["draftboxId": draftboxId ?? ""]
        BFNetRequestAdaptor.postRequestData(url: PQENVUtil.shared.clipapiapi + draftboxGetSdataUrl, parames: params, commonParams: commonParams()) { response, _, error, _ in

            if response is NSNull || response == nil {
                completeHander(nil, error?.msg)
                return
            }
            BFLog(message: "draftboxGetSdata response is \(String(describing: response))")

            let oneProjectModel = Mapper<PQEditSdataModel>().map(JSONString: response as! String)

            completeHander(oneProjectModel, "请求成功")
        }
    }

    /// 素材上报扩展字段
    /// - Parameter materialData: <#materialData description#>
    /// - Returns: <#description#>
    public class func uploadReportExParams(isDownload: Bool, materialData: PQEditVisionTrackMaterialsModel?) -> [String: Any] {
        var params: [String: Any] = ["draftboxId": PQSingletoMemoryUtil.shared.draftboxId ?? "", "materialType": materialData?.type ?? ""]
        if !isDownload {
            params["materialSource"] = (materialData?.localSearchId != nil && (materialData?.localSearchId ?? "").count > 0) ? "netMaterial" : "localMaterial"
        }
        if materialData?.id != nil, (materialData?.id ?? 0) > 0 {
            params["materialId"] = materialData?.id ?? 0
        }
        if materialData?.materialUrl != nil, (materialData?.materialUrl.count ?? 0) > 0 {
            params["materialUrl"] = materialData?.materialUrl ?? ""
        }
        if materialData?.locationPath != nil, materialData?.locationPath.count ?? 0 > 0 {
            params["materialMD5"] = (contentMD5(path: documensDirectory + (materialData?.locationPath ?? ""), data: nil) ?? "")
        }
        BFLog(message: "素材上报扩展字段 = \(params),isDownload = \(isDownload)")
        return params
    }
}
