//
//  YHShareManager.swift
//  galaxy
//
//  Created by EDY on 2024/5/7.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import Alamofire
import AGConnectAppLinking

class YHShareManager: NSObject {
    static let shared = YHShareManager()
    var scene: WXScene = WXSceneSession
    typealias SuccessHandlerType = (String) -> Void
    var success: SuccessHandlerType?
}

extension YHShareManager {
    //拉起微信第三方登录
    func sendLogin() {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "未安装微信App")
            return
        }
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.state = "wechat_sdk_demo_test"
        WXApi.send(req) { flag in
            if !flag {
                YHHUD.flash(message: "分享失败")
            }
        }
    }
    
    func getWechatAccessToken(code: String){
        let url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx06b21f3c7a5ba594&secret=37a83c778aacc0f7788466682ef70c4e&code=\(code)&grant_type=authorization_code"
        var requestHeader = HTTPHeaders()
        requestHeader.add(name:"Conatent-Type",value:"application/json")
        requestHeader.add(name:"Accept",value:"application/json")
        AF.sessionConfiguration.requestCachePolicy = .reloadIgnoringCacheData
        AF.sessionConfiguration.timeoutIntervalForRequest = 20
        let encoding = URLEncoding(destination: .queryString)
        let httpRequest = AF.request(url, method: .get, parameters: nil, encoding:encoding, headers: requestHeader, interceptor: nil, requestModifier: nil)
        
        httpRequest.responseString(completionHandler: { string in
#if DEBUG
            printLog("\n网络请求已返回 string=\(string)")
#endif
            let responseResult = string.result
            var statusCode = string.response?.statusCode ?? 0
            let errorResponseMsg = string.error?.localizedDescription ?? ""
            let resultValue = string.value ?? ""
            let serverDict = resultValue.toDictionary()
            guard let access_token = serverDict["access_token"] as? String, let openid = serverDict["openid"] as? String,let unionid = serverDict["unionid"] as? String else{
                return
            }
            if let block = self.success {
                block(unionid)
            }
//            self.getWechatUserInfo(with: access_token, openId: openid)
        })
    }
    
    func getWechatUserInfo(with access_token:String, openId:String)  {
        let url = "https://api.weixin.qq.com/sns/userinfo?access_token=\(access_token)&openid=\(openId)"
        var requestHeader = HTTPHeaders()
        requestHeader.add(name:"Conatent-Type",value:"application/json")
        requestHeader.add(name:"Accept",value:"application/json")
        AF.sessionConfiguration.requestCachePolicy = .reloadIgnoringCacheData
        AF.sessionConfiguration.timeoutIntervalForRequest = 20
        let encoding = URLEncoding(destination: .queryString)
        let httpRequest = AF.request(url, method: .get, parameters: nil, encoding:encoding, headers: requestHeader, interceptor: nil, requestModifier: nil)
        
        httpRequest.responseString(completionHandler: { string in
#if DEBUG
            printLog("\n网络请求已返回 string=\(string)")
#endif
            let responseResult = string.result
            var statusCode = string.response?.statusCode ?? 0
            let errorResponseMsg = string.error?.localizedDescription ?? ""
            let resultValue = string.value ?? ""
            let serverDict = resultValue.toDictionary()
            guard let openid = serverDict["openid"] as? String, let nickname = serverDict["nickname"] as? String else{
                return
            }
            // 获取到的用户信息json格式，可以拿来给服务端绑定用户信息
            //`在这里绑定获取到的用户信息`
            if let iso88591Data = nickname.data(using: .isoLatin1) {
                if let utf8String = String(data: iso88591Data, encoding: .utf8) {
                    print(utf8String)  // 这是转换为UTF-8后的字符串
                }
            }
        })
    }
    
    func sendTextContect(_ text: String, _ scene: WXScene = WXSceneSession) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "未安装微信App")
            return
        }
        let req = SendMessageToWXReq()
        req.bText = true
        req.text = text
        req.scene = Int32(scene.rawValue)
        WXApi.send(req) { flag in
            if !flag {
                YHHUD.flash(message: "分享失败")
            }
        }
    }
    
    func sendLinkContent(_ title: String = "", _ description: String = "", _ image: UIImage = UIImage(), link: String, _ scene: WXScene = WXSceneSession) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "未安装微信App")
            return
        }
        let message =  WXMediaMessage()
    
        message.title = title
        message.description = description
        
        if image.size.width > 0 {
            let width = 240.0 as CGFloat
            let height = width*image.size.height/image.size.width
            UIGraphicsBeginImageContext(CGSizeMake(width, height))
            image.draw(in: CGRectMake(0, 0, width, height))
            message.setThumbImage(UIGraphicsGetImageFromCurrentImageContext() ?? UIImage())
            UIGraphicsEndImageContext()
        }
         
        let ext =  WXWebpageObject()
        ext.webpageUrl = link
        message.mediaObject = ext
         
        let req =  SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(scene.rawValue)
        WXApi.send(req) { flag in
            if !flag {
                YHHUD.flash(message: "分享失败")
            }
        }
    }
    
    func sendVideoContent(_ title: String = "", _ description: String = "", _ image: UIImage = UIImage(), link: String, _ scene: WXScene = WXSceneSession) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "未安装微信App")
            return
        }
        let message =  WXMediaMessage()
    
        message.title = title
        message.description = description
        let width = 240.0 as CGFloat
        let height = width*image.size.height/image.size.width
        UIGraphicsBeginImageContext(CGSizeMake(width, height))
        image.draw(in: CGRectMake(0, 0, width, height))
        message.setThumbImage(UIGraphicsGetImageFromCurrentImageContext() ?? UIImage())
        UIGraphicsEndImageContext()
         
        let ext =  WXVideoObject()
        ext.videoUrl = link
        message.mediaObject = ext
         
        let req = SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(scene.rawValue)
        WXApi.send(req) { flag in
            if !flag {
                YHHUD.flash(message: "分享失败")
            }
        }
    }
    
    func sendImageContent(_ image: UIImage, _ scene: WXScene = WXSceneSession) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "未安装微信App")
            return
        }
        let message =  WXMediaMessage()
                
        //发送的图片
        let imageObject =  WXImageObject()
        imageObject.imageData = image.pngData() ?? Data()
        message.mediaObject = imageObject
       //图片缩略图
        let width = 240.0 as CGFloat
        let height = width*image.size.height/image.size.width
        UIGraphicsBeginImageContext(CGSizeMake(width, height))
        image.draw(in: CGRectMake(0, 0, width, height))
        message.setThumbImage(UIGraphicsGetImageFromCurrentImageContext() ?? UIImage())
        UIGraphicsEndImageContext()
        
        let req = SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(scene.rawValue)
        WXApi.send(req) { flag in
            if !flag {
                YHHUD.flash(message: "分享失败")
            }
        }
    }
    
    /*
     分享文件到微信
     */
    
    func shareFileToWeChat(fileUrl: URL, filename: String, ext: String) {
        // 检查微信是否安装
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "未安装微信App")
            return
        }
        guard let fileData = try? Data(contentsOf: fileUrl) else {
            YHHUD.flash(message: "本地不存在该文件")
            return
        }
        // 文件大小检查
        let fileSize = fileData.count / 1024 / 1024 // MB
        guard fileSize <= 10 else { // 微信限制10MB
            YHHUD.flash(message: "文件超过10MB")
            return
        }
        // 创建文件对象
        let fileObject = WXFileObject()
        fileObject.fileData = fileData
        fileObject.fileExtension = ext
        
        // 创建消息体
        let message = WXMediaMessage()
        message.title = filename
        message.description = ""
//        message.thumbData = UIImage(named: "pdf_thumb")?.pngData() // 缩略图，不超过32KB
        message.mediaObject = fileObject
        
        // 创建发送请求
        let req = SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(WXSceneSession.rawValue)  // 发送到会话
        // 发送请求
        WXApi.send(req) { success in
            if !success {
                YHHUD.flash(message: "发送失败")
            }
        }
    }
    
    /*
     分享到微信小程序
     */
    func shareToMiniProgram(path: String,  shareTitle: String,shareImageName : String = "my_doc_share") {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "未安装微信App")
            return
        }
        let iamge = UIImage(named: shareImageName) ?? UIImage()
        
        let message =  WXMediaMessage()
       
        //发送的小程序
        let object =  WXMiniProgramObject()
        object.path = path
        object.webpageUrl = ""
        object.userName = "gh_35ddbd2e68d4"
        
#if DEBUG
        object.miniProgramType = .preview
#elseif TESTENV
        object.miniProgramType = .preview
#else
        object.miniProgramType = .release
#endif
        
        
        
        message.mediaObject = object
        message.title = shareTitle//"您的朋友邀请您点击小程序，协作签署\(name)"
//        message.description = "有文书分享转发给您，需要您帮忙签署，快来看看吧~"
//        message.thumbData = nil
        message.setThumbImage(iamge)

        let req = SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(scene.rawValue)
        WXApi.send(req) { flag in
            if !flag {
                YHHUD.flash(message: "分享失败")
            }
        }
    }
    
    // 拉起小程序
    func openMiniProgram(path: String, title: String) {
        
        let miniProgram = WXLaunchMiniProgramReq.object()// 小程序原始ID，小程序信息可查看，以gh_开头
        miniProgram.userName = "gh_35ddbd2e68d4"
        // 小程序页面路径
        miniProgram.path = path
#if DEBUG
        miniProgram.miniProgramType = .preview
#elseif TESTENV
        miniProgram.miniProgramType = .preview
#else
        miniProgram.miniProgramType = .release
#endif
        WXApi.send(miniProgram)
        
    }
    
    /*
     生成多平台分享链接,完成回环操作
     type :  业务类型 1-直播
     param : 业务对应的参数
     */
    func createMutilShareUrl(type: Int,param : [String : String]) -> String? {
        if type < 1 {
            return nil
        }
        
        //直播 分享连接
        let components = AGCAppLinkingComponents()
        
        //通过urlPrefix属性设置为申请链接前缀中的链接前缀
        components.uriPrefix = YhConstant.DeepLink.urlPreUrlFix
        
        //通过deepLink属性设置深度链接地址
        var linkUrl = YhConstant.DeepLink.url + "?" + "type=\(type)"
        
        let arrKey = param.keys
        for (_,item) in arrKey.enumerated() {
            if let value = param[item],!value.isEmpty {
                linkUrl = linkUrl + "&" + item + "=" + value
            }
        }
        
        components.deepLink = linkUrl
        components.iosBundleId = Bundle.main.bundleIdentifier
        components.androidDeepLink = linkUrl //安卓平台调用不过 所以需要单独写出来
        components.androidPackageName = "com.galaxy.galaxyandroid"
        
        let url = components.buildLongLink()
        return url.absoluteString
    }
    
    
    func createMutilShareShortUrl(type: Int,param : [String : String],callBack: @escaping ((String?,Error?) -> Void)) {
        if type < 1 {
            callBack(nil,nil)
            return
        }
        
        //直播 分享连接
        let components = AGCAppLinkingComponents()
        
        //通过urlPrefix属性设置为申请链接前缀中的链接前缀
        components.uriPrefix = YhConstant.DeepLink.urlPreUrlFix
        
        //通过deepLink属性设置深度链接地址
        var linkUrl = YhConstant.DeepLink.url + "?" + "type=\(type)"
        
        let arrKey = param.keys
        for (_,item) in arrKey.enumerated() {
            if let value = param[item],!value.isEmpty {
                linkUrl = linkUrl + "&" + item + "=" + value
            }
        }
        
        components.deepLink = linkUrl
        components.iosBundleId = Bundle.main.bundleIdentifier
        components.androidDeepLink = linkUrl //安卓平台调用不过 所以需要单独写出来
        components.androidPackageName = "com.galaxy.galaxyandroid"
        components.buildShortLink { shortLink, error in
            callBack(shortLink?.url.absoluteString, error)
        }
    }
}
