//
//  ZNetUtil.swift
//  SwiftProject
//
//  Created by aaa on 2024/4/12.
//

import Foundation
import AdSupport
import DeviceKit
class ZNetUtil: NSObject {
    // 新建项目默认已配置DEBUG,可以用BEBUG来判断
    #if DEBUG
    static let hostUrl = "https://openapi.lux-ad.com"
    #else
    static let hostUrl = "https://openapi.lux-ad.com"
    #endif

    static let userId = UIDevice.current.identifierForVendor?.uuidString ?? "unknow_userid"
    static let pkgName = Bundle.main.bundleIdentifier ?? "com.nsk.tdvideo"
    //上报app信息
    static let kUploadAppInfoUrl:String = hostUrl + "/statistic/appdatacollection/saveAppData"
    
    //用户反馈  参数:  catalog 问题标题  remark 问题描述   contact 联系方式
    static let kUserFeedbackUrl:String = hostUrl + "/app/common/createFeedback"
    
    class func postUrl(urlStr:String,params:[String:Any], callback:@escaping (_ result:[String:Any]?, _ error:Error?)->Void){
        let url = URL(string: urlStr)
        guard let url else {
            return
        }
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        let comParams = getComParams()
        let nparams = params.merging(comParams) { va, ke in
            
        }
        let bodyData = try? JSONSerialization.data(withJSONObject: nparams, options: [])
        request.httpBody = bodyData
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue(ZNetUtil.userId, forHTTPHeaderField: "request_userid")
        request.addValue(ZNetUtil.pkgName, forHTTPHeaderField: "request_pkgname")
        let dataTask = URLSession.shared.dataTask(with: request) { data, response, error in
//            print("response:\(response)")
            DispatchQueue.main.async {
                if let error = error {
                    print("Error:", error)
                    callback(nil,error)
                    return
                }

                guard let data = data, let response = response as? HTTPURLResponse else {
                    print("Invalid response")
                    callback(nil,nil)
                    return
                }
                let result = try? JSONSerialization.jsonObject(with: data) as? [String:Any]
                callback(result,nil)
            }
        }
        dataTask.resume()
    }
    
    
    
    //返回通用参数
    class func getComParams()->[String:Any] {
        let infoDictionary: Dictionary = Bundle.main.infoDictionary!
        
        let userId = ZNetUtil.userId
        let ad_id = ASIdentifierManager.shared().advertisingIdentifier.uuidString
        let uuid = ZZHHelper.getUUID()
        let device = UIDevice.current.phoneModel
        let appVersion = infoDictionary["CFBundleShortVersionString"] as! String
        let language = ZZHHelper.getCurrentLanguage()
        let pkgName = ZNetUtil.pkgName
        let country = ZZHHelper.getCurrentRegion()
        let timestamp = Date.now.timeIntervalSince1970
        let params = ["userId":userId,
                      "ad_id":ad_id,
                      "uuid":uuid,
                      "device":device,
                      "appVersion":appVersion,
                      "language":language,
                      "channel":"ios",
                      "pkgName":pkgName,
                      "country":country,
                      "timestamp":timestamp] as [String : Any]
        return params
    }
}
