//
//  QSWikiHandle.swift
//  QuickSearchLocation
//
//  Created by Destiny on 2025/7/17.
//

import Foundation
import Alamofire
import SwiftyJSON
import AdSupport

class QSWikiHandle {
    
    static let shared = QSWikiHandle()
    
    var hostUrl = "http://asafrontend.mokiwi.com/api"
    
    var orgId = "8842660"
    
    var sign = "b14edba8e6ad47565f3d396e05c6560e&kiwi".md5
    
    var requestId : String = ""
    
    func addAttributionResultReport(completion:@escaping ((Bool) -> ())) {
        
        if self.payDataParameterNotExist() {
            completion(false)
            return
        }
        
        var dict: [String: Any] = [String: Any]()
        if let payLoad: [String: Any] = UserDefaults.standard.object(forKey: "QS_ATTRIBUTION_PAYLOAD") as? [String : Any] {
            
            if let campaignId = payLoad["campaignId"] as? Int {
                dict["campaign_id"] = campaignId
            }
            
            if let adGroupId = payLoad["adGroupId"] as? Int {
                dict["ad_group_id"] = adGroupId
            }

            
            if let keywordId = payLoad["keywordId"] as? Int {
                dict["keyword_id"] = keywordId
            }
            
            let date = Date()
            let formatter = DateFormatter()
            formatter.timeZone = TimeZone.autoupdatingCurrent
            formatter.dateFormat = "yyyy-MM-dd"
            let todayDate = formatter.string(from: date)
            dict["date"] = todayDate
            dict["timezone"] = "ORTZ"
        }
        
        let urlString = String(format: "%@/asabackendData/add?org_id=%@&sign=%@",hostUrl,orgId,sign)
        
        let headers = ["Content-Type": "application/json"]
        
        // 使用Alamofire发送POST请求
        AF.request(urlString, method: .post, parameters: dict, encoding: JSONEncoding.default, headers: HTTPHeaders(headers)).response { response in
            switch response.result {
            case .success(let value):
                let json = try? JSON(data: value ?? Data())
                print("QSWikiHandle responseObject: \(String(describing: json))")
                if json?["code"] == 10000 {
                    print("QSWikiHandle asa用户 提交成功")
                    
                    // 正确提取 request_id（根据实际类型调整）
                    if let requestIdString = json?["request_id"].string {
                        self.requestId = requestIdString  // 假设 requestId 是 String 类型
                        print("提取到的 request_id: \(requestIdString)")
                    } else if let requestIdInt = json?["request_id"].int {
                        self.requestId = String(requestIdInt)  // 如果是 Int 类型，转换为 String
                        print("提取到的 request_id: \(requestIdInt)")
                    } else {
                        print("警告: 无法解析 request_id")
                    }
                    
                    completion(true)
                } else {
                    print("QSWikiHandle asa用户 提交失败")
                    completion(false)
                }
            case .failure(let error):
                print("QSWikiHandle asa用户 error: \(error)")
                completion(false)
            }
        }
    }
    
    func addEventResultAttribution(eventDict: [String: Any]) {
        print("QSWikiHandle asa用户 参数输入\(eventDict)")
        if self.payDataParameterNotExist() {
            return
        }
        
        var dict: [String: Any] = [String: Any]()
        if let payLoad: [String: Any] = UserDefaults.standard.object(forKey:"QS_ATTRIBUTION_PAYLOAD") as? [String : Any] {
        
            if let campaignId = payLoad["campaignId"] as? Int {
                dict["campaign_id"] = campaignId
            }

            if let adGroupId = payLoad["adGroupId"] as? Int {
                dict["ad_group_id"] = adGroupId
            }
            
            if let keywordId = payLoad["keywordId"] as? Int {
                dict["keyword_id"] = keywordId
            }
            
            dict["request_id"] = self.requestId
            
            let date = Date()
            let formatter = DateFormatter()
            formatter.timeZone = TimeZone.autoupdatingCurrent
            formatter.dateFormat = "yyyy-MM-dd"
            let todayDate = formatter.string(from: date)
            dict["date"] = todayDate
            dict["timezone"] = "ORTZ"
            
            // 用户已授权
            let idfaStr = ASIdentifierManager.shared().advertisingIdentifier.uuidString
            if idfaStr.count > 0 {
                dict["unique_device"] = idfaStr
            } else {
                let idfv = UIDevice.current.identifierForVendor?.uuidString
                dict["unique_device"] = idfv
            }
        }
        
        for (key, value) in eventDict {
            dict[key] = value
        }
        
        let urlString = String(format: "%@/asabackendDataDetail/add?org_id=%@&sign=%@",hostUrl,orgId,sign)
        print("usdfStringgsdfs--\(urlString)");
        
        let headers = ["Content-Type": "application/json"]
        
        let parameters = ["backend_data_detail": dict]
        
        // 使用Alamofire发送POST请求
        AF.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: HTTPHeaders(headers)).response { response in
            switch response.result {
            case .success(let value):
                let json = try? JSON(data: value ?? Data())
                print("QSWikiHandle responseObject: \(String(describing: json))")
                if json?["code"] == 10000 {
                    print("QSWikiHandle asa用户 提交成功")
                } else {
                    print("QSWikiHandle asa用户 提交失败 --- \(parameters)")
                }
            case .failure(let error):
                print("QSWikiHandle asa用户 error: \(error)")
            }
        }
    }
    
    func payDataParameterNotExist() -> Bool {
        guard UserDefaults.standard.object(forKey:"QS_ATTRIBUTION_PAYLOAD") is [String: Any] else {
            return true
        }
        return false
    }
}
