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

import UIKit
import Alamofire

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: "拉起微信失败")
            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) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "拉起微信失败")
            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) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "拉起微信失败")
            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 =  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) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "拉起微信失败")
            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) {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "拉起微信失败")
            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 sendMiniProgram() {
        guard WXApi.isWXAppInstalled() else {
            YHHUD.flash(message: "拉起微信失败")
            return
        }
        let message =  WXMediaMessage()
                
        //发送的小程序
        let object =  WXMiniProgramObject()
        object.path = ""
        object.webpageUrl = ""
        object.userName = "gh_35ddbd2e68d4"
        message.mediaObject = object
        message.title = "智汇银河"
        message.description = "小程序"
        message.thumbData = nil
        
        let req = SendMessageToWXReq()
        req.bText = false
        req.message = message
        req.scene = Int32(scene.rawValue)
        WXApi.send(req) { flag in
            if !flag {
                YHHUD.flash(message: "分享失败")
            }
        }
    }
}
