//
//  YHLiveSalesViewModel.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/27.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHLiveSalesViewModel: YHBaseViewModel {
    // 直播间详情
    var liveDetailModel: YHLiveDetailModel?
    // 录播详情
    var recordedDetailModel: YHRecordedDetailModel?

    // 注册环信用户信息
    var huanXinUserInfoModel: YHHuanXinUserModel?
    
    // 获取环信Token信息
    var huanXinTokenModel: YHHuanXinTokenModel?
    // 快速生成订单
    var orderModel: YHLiveCreateOrderModel?
    var livePeople: YHLivePeopleModel?
}

extension YHLiveSalesViewModel {
    /*
     注册环信用户
     */
    func registerHuanXinUser(callBackBlock: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.registerHuanXinUserApi
        _ = YHNetRequest.postRequest(url: strUrl) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHHuanXinUserModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callBackBlock(false, err)
                    return
                }
                self.huanXinUserInfoModel = resultModel
                callBackBlock(true, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(false, err)
            }

        } failBlock: { err in
            callBackBlock(false, err)
        }
    }
    
    /*
     环信Token信息
     */
    func getHuanXinToken(callback: @escaping (_ tokenModel: YHHuanXinTokenModel?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.fetchHuanXinToken
        _ = YHNetRequest.getRequest(url: strUrl, params: [:]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHHuanXinTokenModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback(nil, err)
                    return
                }
                self?.huanXinTokenModel = resultModel
                callback(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(nil, err)
            }

        } failBlock: { err in
            callback(nil, err)
        }
    }

    /*
     直播间详情
     */
    func getLiveDetail(id: Int, callback: @escaping (_ liveDetail: YHLiveDetailModel?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.liveDetail
        _ = YHNetRequest.getRequest(url: strUrl, params: ["id": id]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHLiveDetailModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback(nil, err)
                    return
                }
                self?.liveDetailModel = resultModel
                callback(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(nil, err)
            }

        } failBlock: { err in
            callback(nil, err)
        }
    }
    
    /*
     点播详情
     */
    func getRecordedDetail(id: Int, callback: @escaping (_ recordedDetail: YHRecordedDetailModel?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.recordedDetail
        _ = YHNetRequest.getRequest(url: strUrl, params: ["id": id]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHRecordedDetailModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback(nil, err)
                    return
                }
                self?.recordedDetailModel = resultModel
                callback(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(nil, err)
            }

        } failBlock: { err in
            callback(nil, err)
        }
    }
    
    /*
     离开直播间
     */
    func leaveLiveRoom(id: Int, callback: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.leaveLiveRoom
        _ = YHNetRequest.getRequest(url: strUrl, params: ["live_id": id]) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                callback(true, nil)
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(false, err)
            }

        } failBlock: { err in
            callback(false, err)
        }
    }
    
    /*
     进入直播间
     */
    func joinLiveRoom(id: Int, callback: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.joinLiveRoom
        _ = YHNetRequest.getRequest(url: strUrl, params: ["live_id": id]) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                callback(true, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(false, err)
            }

        } failBlock: { err in
            callback(false, err)
        }
    }
    
    /*
     注册环信用户  "source": 0,  // 1直播 2 录播
     "source_id": 0, // 直播或录播id
     "product": {
       "id": 0
     }
     */
    func createOrder(source: Int, sourceId: Int, productId: Int, callBackBlock: @escaping (_ orderModel: YHLiveCreateOrderModel?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.createOrder
        let product: [String: Int] = ["id": productId]
        let params: [String: Any] = ["source": source, "source_id": sourceId, "product": product]
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHLiveCreateOrderModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callBackBlock(nil, err)
                    return
                }
                self?.orderModel = resultModel
                callBackBlock(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callBackBlock(nil, err)
            }
        } failBlock: { err in
            callBackBlock(nil, err)
        }
    }
    
    func getLivePeople(id: Int, callback: @escaping (_ livePeople: YHLivePeopleModel?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.livePeople
        _ = YHNetRequest.getRequest(url: strUrl, params: ["live_id": id]) { [weak self] json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHLivePeopleModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback(nil, err)
                    return
                }
                self?.livePeople = resultModel
                callback(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(nil, err)
            }

        } failBlock: { err in
            callback(nil, err)
        }
    }
    
    func postLiveBook(id: Int, callback: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["live_id": id, "source_type": 1]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.liveBook
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { [weak self] json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                callback(true, nil)
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(false, err)
            }

        } failBlock: { err in
            callback(false, err)
        }
    }
    
    func getRecommendLiveList(callback: @escaping (_ liveList: YHRecommendLiveListModel?, _ error: YHErrorModel?) -> Void) {
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.recommendLiveList
        _ = YHNetRequest.getRequest(url: strUrl, params: [:]) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHRecommendLiveListModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback(nil, err)
                    return
                }
                callback(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(nil, err)
            }

        } failBlock: { err in
            callback(nil, err)
        }
    }
    
    func getShareLiveInfo(liveId: Int, shareType: Int, callback: @escaping (_ liveInfo: YHShareLiveInfoModel?, _ error: YHErrorModel?) -> Void) {
        // 分享类型 1:直播 2录播
        let param: [String: Any] = ["live_id": liveId, "share_type": shareType]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.shareLive
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHShareLiveInfoModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback(nil, err)
                    return
                }
                callback(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(nil, err)
            }

        } failBlock: { err in
            callback(nil, err)
        }
    }
    
    func getLiveStatus(liveId: Int, callback: @escaping (_ liveInfo: YHLiveStatusModel?, _ error: YHErrorModel?) -> Void) {
        // 分享类型 1:直播 2录播
        let param: [String: Any] = ["live_id": liveId]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.liveStatus
        _ = YHNetRequest.getRequest(url: strUrl, params: param) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")

            if json.code == 200 {
                guard let dic = json.data?.peel as? [String: Any], let resultModel = YHLiveStatusModel.deserialize(from: dic) else {
                    let err = YHErrorModel(errorCode: YHErrorCode.dictParseError.rawValue, errorMsg: YHErrorCode.dictParseError.description())
                    callback(nil, err)
                    return
                }
                callback(resultModel, nil)

            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(nil, err)
            }

        } failBlock: { err in
            callback(nil, err)
        }
    }
    
    func postLiveViewRecords(id: Int, userId: String, sourceType: Int, callback: @escaping (_ success: Bool, _ error: YHErrorModel?) -> Void) {
        let params: [String: Any] = ["live_id": id,
                                     "from_user_id": userId,
                                     "view_port": 1,
                                     "source_type": sourceType
        ]
        let strUrl = YHBaseUrlManager.shared.curURL() + YHAllApiName.LiveSales.viewRecords
        _ = YHNetRequest.postRequest(url: strUrl, params: params) { json, _ in
            // 1. json字符串 转 对象
            printLog("model 是 ==> \(json)")
            if json.code == 200 {
                callback(true, nil)
            } else {
                let err = YHErrorModel(errorCode: Int32(json.code), errorMsg: json.msg.isEmpty ? "" : json.msg)
                callback(false, err)
            }

        } failBlock: { err in
            callback(false, err)
        }
    }

}

private extension String {
    var timeStamp: String {
        let date = Date()
        let timeInterval = date.timeIntervalSince1970
        let millisecond = CLongLong(timeInterval * 1000)
        return "\(millisecond)"
    }
}
