//
//  YHImagePickerView.swift
//  galaxy
//
//  Created by EDY on 2024/1/30.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

/*
 let view = YHImagePickerView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
 view.backImage = { [weak self] image in
     guard let self = self else { return }
 }
 let window = UIApplication.shared.yhKeyWindow()
 window?.addSubview(view)
 */

import UIKit
import Alamofire
import Photos

class YHImagePickerView: UIView {
    var backImage: ((UIImage) -> Void)?
    var centerView: UIView!
    var titleLabel: UILabel!
    var closeButton: UIButton!
    var takePhotoBtton: UIButton!
    var selectPhotoButton: UIButton!
    var cannalButton: UIButton!
    var lineView: UIView!
    
    static func show(callBack: @escaping ((UIImage) -> Void)) {
        let view = YHImagePickerView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.backImage = callBack
        let window = UIApplication.shared.yhKeyWindow()
        window?.addSubview(view)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor(white: 0.5, alpha: 0.1)
        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        tap.delegate = self
        addGestureRecognizer(tap)
        setView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setView() {
        backgroundColor = UIColor(hex: 0x0000, alpha: 0.5)
        centerView = {
            let view = UIView()
            view.backgroundColor = .white
            view.layer.cornerRadius = kCornerRadius8
            return view
        }()
        addSubview(centerView)
        centerView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(244)
        }
        
        titleLabel = {
            let label = UILabel()
            label.text = "请选择上传方式"
            label.font = UIFont.PFSC_M(ofSize: 17)
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .center
            return label
        }()
        centerView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(16)
            make.left.height.equalTo(21)
            make.right.equalTo(-21)
        }
        
        closeButton = {
            let button = UIButton(type: .custom)
            button.setBackgroundImage(UIImage(named: "service_card_close"), for: .normal)
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.width.height.equalTo(24)
            make.top.equalTo(16)
        }
        
        takePhotoBtton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
            button.contentHorizontalAlignment = .center
            button.setTitle("拍照上传", for: .normal)
            button.setTitleColor( UIColor.mainTextColor, for: .normal)
            button.addTarget(self, action: #selector(takePhoto), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(takePhotoBtton)
        takePhotoBtton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.equalTo(51)
            make.left.equalTo(21)
            make.top.equalTo(53)
        }
        
        selectPhotoButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
            button.contentHorizontalAlignment = .center
            button.setTitle("相册上传", for: .normal)
            button.setTitleColor( UIColor.mainTextColor, for: .normal)
            button.addTarget(self, action: #selector(selectPhoto), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(selectPhotoButton)
        selectPhotoButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.equalTo(51)
            make.left.equalTo(21)
            make.top.equalTo(105)
        }
        
        cannalButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
            button.contentHorizontalAlignment = .center
            button.setTitle("取消", for: .normal)
            button.setTitleColor( UIColor(hex:0x909090), for: .normal)
            button.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
            return button
        }()
        centerView.addSubview(cannalButton)
        cannalButton.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.height.equalTo(51)
            make.left.equalTo(21)
            make.top.equalTo(156)
        }
        
        for i in 0..<3 {
            let view = UIView()
            view.backgroundColor = UIColor.separatorColor
            centerView.addSubview(view)
            view.snp.makeConstraints { make in
                make.left.equalTo(18)
                make.top.equalTo(52 + 52 * i)
                make.height.equalTo(1)
                make.right.equalTo(-18)
            }
        }
    }
    
    @objc private func handleTap(_ sender: AnyObject?) {
        print("处理点击手势")
        dismiss()
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
    @objc func takePhoto() {
        guard getPhotoLibraryAuthorization() else { return }
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //创建图片控制器
            let imagePicker = UIImagePickerController()
            //设置代理
            imagePicker.delegate = self
            //设置来源
            imagePicker.sourceType = .camera
            //打开相机
            UIViewController.current?.present(imagePicker, animated: true, completion: { () -> Void in
                 
            })
        } else {
            printLog("找不到相机")
        }
    }
    
    @objc func selectPhoto() {
        guard getPhotoLibraryAuthorization() else { return }
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            // 这一句，开始调用图库
            UIViewController.current?.present(imagePicker,animated: true)
        }
    }
    
    private func getPhotoLibraryAuthorization() -> Bool {
        let authorizationStatus = PHPhotoLibrary.authorizationStatus()
        switch authorizationStatus {
        case .authorized:
            print("已经授权")
            return true
        case .notDetermined:
            print("不确定是否授权")
            // 请求授权
            PHPhotoLibrary.requestAuthorization({ (status) in })
        case .denied:
            print("拒绝授权")
        case .restricted:
            print("限制授权")
            break
        case .limited: break
        @unknown default:
            break
        }
        return false
    }
}

extension YHImagePickerView: UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer:UIGestureRecognizer, shouldReceive touch:UITouch) -> Bool {
        if touch.view == self {
            return true
        }
        return false
    }
}

extension YHImagePickerView: UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            if let block = backImage {
                block(image)
                self.dismiss()
            }
        } else {
            printLog("pick image wrong")
        }
        // 收回图库选择界面
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }

//    //原生上传
//    func uploadImage(imageURL: URL) {
//        let url = URL(string: "https://test-comserver.galaxy-immi.com/oss/upload/storage")! // 设置上传接口地址
//        
//        var request = URLRequest(url: url)
//        request.httpMethod = "POST"
//        
//        do {
//            let imageData = try Data(contentsOf: imageURL) // 读取要上传的图片数据
//            
//            let boundary = UUID().uuidString // 生成随机边界字符串
//            request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
//            request.addValue("4001001", forHTTPHeaderField: "businessCode")
//
//            var body = ""
//            body += "--\(boundary)\r\n"
//            body += "Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n" // 根据需求修改文件名称
//            body += "Content-Type: image/jpeg\r\n\r\n" // 根据实际情况指定正确的MIME类型
//            if let data = imageData.base64EncodedString(options: .lineLength76Characters).addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics) {
//                let encodedBody = body + "\r\n" + data + "\r\n" + "--" + boundary + "--"
//                    guard let postData = encodedBody.data(using: String.Encoding.utf8) else { return }
//                    
//                    request.httpBody = postData
//                    
//                    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
//                        if let error = error {
//                            print("Error: \(error)")
//                        } else if let httpResponse = response as? HTTPURLResponse {
//                            switch httpResponse.statusCode {
//                            case 200..<300:
//                                if let data = data {
//                                    let string = String(data: data, encoding: .utf8)
//                                    
//                                }
//                                print("Upload successful.")
//                            default:
//                                print("Failed to upload the image with status code: \(httpResponse.statusCode)")
//                            }
//                        }
//                    }
//                    task.resume()
//                }
//            } catch {
//                print("Error reading image file: \(error)")
//            }
//    }
    
//    // Alamofire上传
//    func uploadImage(image: UIImage) {
//        // 获取图片的二进制数据
//        guard let imageData = image.jpegData(compressionQuality: 1) else { return }
//        let boundary = UUID().uuidString
//        let headers: HTTPHeaders = [
//            "Content-type": "multipart/form-data; boundary=\(boundary)",
//            "businessCode": "4001001"
//        ]
//        // 创建MultipartFormData对象
//        let multipartFormData = MultipartFormData()
//        
//        // 将图片添加到multipartFormData中
//        multipartFormData.append(imageData, withName: "file", fileName: "image.jpg", mimeType: "image/jpeg")
//        
//        // 发送POST请求
//        let uploadRequest = AF.upload(multipartFormData: multipartFormData, to: "https://test-comserver.galaxy-immi.com/oss/upload/storage", headers: headers)
//        
//        uploadRequest.responseString(completionHandler: { string in
//            printLog("\n网络请求已返回 string=\(string)")
//        })
//    }
}

extension YHImagePickerView {
    func checkImage( _image : UIImage) -> UIImage? {
        let size = _image.imageSize()
        if size > 4 * 1024 * 1024 {
//            let  data  = _image.compressOriginalImage(toKb: 4 * 1024)
            
            if let data = _image.compressOriginalImage(4 * 1024 * 1024), let ttt = UIImage(data: data) {
                return ttt
            }
        }
        return _image
    }
}

