//
//  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

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!
    
    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 = 16
            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 = kFont(size: 17)
            label.textColor = UIColor(hex:0x222222)
            label.textAlignment = .left
            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 = kBoldFont(size: 14)
            button.contentHorizontalAlignment = .center
            button.setTitle("拍照上传", for: .normal)
            button.setTitleColor( UIColor(hex:0x222222), 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 = kBoldFont(size: 14)
            button.contentHorizontalAlignment = .center
            button.setTitle("相册上传", for: .normal)
            button.setTitleColor( UIColor(hex:0x222222), 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 = kBoldFont(size: 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(hex: 0xf0f0f0)
            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() {
        if UIImagePickerController.isSourceTypeAvailable(.camera){
            //创建图片控制器
            let imagePicker = UIImagePickerController()
            //设置代理
            imagePicker.delegate = self
            //设置来源
            imagePicker.sourceType = .camera
            //允许编辑
            imagePicker.allowsEditing = true
            //打开相机
            UIViewController.current?.present(imagePicker, animated: true, completion: { () -> Void in
                 
            })
        } else {
            printLog("找不到相机")
        }
    }
    
    @objc func selectPhoto() {
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = .photoLibrary
            imagePicker.allowsEditing = true
            // 这一句，开始调用图库
            UIViewController.current?.present(imagePicker,animated: true)
        }
    }
}

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 {
        // 将图片显示给UIImageView
            if let block = backImage {
                block(image)
                self.dismiss()
            }
        } else {
            printLog("pick image wrong")
        }
        // 收回图库选择界面
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        
    }
    
}
