//
//  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(_ title: String = "请选择上传方式", callBack: @escaping ((UIImage) -> Void)) {
        let view = YHImagePickerView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: KScreenHeight))
        view.backImage = callBack
        view.titleLabel.text = title
        if title != "请选择上传方式" {
            view.takePhotoBtton.setTitle("拍照", for: .normal)
            view.selectPhotoButton.setTitle("从相册中选择", for: .normal)
        }
        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()
    }
    
    // 请求相机权限
    @objc func takePhoto() {
        AVCaptureDevice.requestAccess(for: .video) { [weak self] granted in
            if granted {
                // 已获得权限,可以使用相机
                DispatchQueue.main.async {
                    if UIImagePickerController.isSourceTypeAvailable(.camera){
                        //创建图片控制器
                        let imagePicker = UIImagePickerController()
                        //设置代理
                        imagePicker.delegate = self
                        //设置来源
                        imagePicker.sourceType = .camera
                        //打开相机
                        UIViewController.current?.present(imagePicker, animated: true, completion: { () -> Void in
                            
                        })
                    } else {
                        printLog("找不到相机")
                    }
                }
            } else {
                DispatchQueue.main.async {
                    YHHUD.flash(message: "请打开相机权限")
                }
            }
        }
    }
    
    // 请求相册权限
    @objc func selectPhoto() {
        PHPhotoLibrary.requestAuthorization { [weak self] status in
            if status == .authorized {
                DispatchQueue.main.async {
                    if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
                        let imagePicker = UIImagePickerController()
                        imagePicker.delegate = self
                        imagePicker.sourceType = .photoLibrary
                        imagePicker.modalPresentationStyle = .fullScreen
                        // 这一句，开始调用图库
                        UIViewController.current?.present(imagePicker,animated: true)
                    }
                }
            } else {
                // 未获得权限,提示用户
                DispatchQueue.main.async {
                    YHHUD.flash(message: "请打开相册权限")
                }
            }
        }
    }

    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?) {
        dismiss()
    }
    
    @objc func dismiss() {
        removeFromSuperview()
    }
    
}

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)
    }
}

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

