//
//  YHCertificateUploadSheetView.swift
//  galaxy
//
//  Created by edy on 2024/3/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//
/*
【Usage】
 
 YHCertificateUploadSheetView.sheetView.show {
    [weak self] actionType in
    guard let self = self else { return }
    print("%d", actionType.rawValue)
 }

 */

import UIKit
import Photos

enum YHCertificateUploadType: Int {
    
    case sample = 1
    case camera = 2
    case photo = 3
    case phoneFile = 4
    case cancel = 5
}

class YHCertificateUploadItem {
    var type: YHCertificateUploadType
    var title: String
    var subtitle: String
    init(type:YHCertificateUploadType, title: String, subtitle: String = "") {
        self.type = type
        self.title = title
        self.subtitle = subtitle
    }
}

class YHCertificateUploadItemView: UIView {
    
    let item: YHCertificateUploadItem
    lazy var topLine:UIView = {
       let view = UIView()
       view.backgroundColor = .separatorColor
       return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_M(ofSize:14)
        return label
    }()
    
    lazy var subTitleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.labelTextColor2
        label.textAlignment = .center
        label.font = UIFont.PFSC_R(ofSize:11)
        return label
    }()
    
    init(_ item: YHCertificateUploadItem) {
        self.item = item
        super.init(frame:CGRect(x: 0, y: 0, width: KScreenWidth, height: 52.0))
        self.createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUI() {
        
        self.tag = self.item.type.rawValue
        
        self.addSubview(titleLabel)
        self.addSubview(subTitleLabel)
        self.addSubview(topLine)
                
        titleLabel.text = item.title
        subTitleLabel.text = item.subtitle
        subTitleLabel.isHidden = item.subtitle.isEmpty
        
        if item.type == .cancel {
            titleLabel.textColor = UIColor(hexString:"#909090")
        }
        
        titleLabel.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.left.right.equalToSuperview()
            if item.subtitle.isEmpty {
                make.centerY.equalToSuperview()
            } else {
                make.bottom.equalTo(self.snp.centerY)
            }
        }
        
        subTitleLabel.snp.makeConstraints { make in
            make.height.equalTo(16)
            make.left.right.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom)
        }
        
        topLine.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview()
            make.height.equalTo(1)
        }
    }
}

class YHCertificateSampleTemplateView: UIView {
    
    lazy var iconImgV: UIImageView = {
        let imgView = UIImageView(image:UIImage(named:"my_cer_template"))
        return imgView
    }()
    
    lazy var arrowImgV: UIImageView = {
        let imgView = UIImageView(image:UIImage(named:"form_right_arrow"))
        return imgView
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "查看证件示例模版".local
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .left
        label.font = UIFont.PFSC_B(ofSize:14)
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func createUI() {
        
        self.backgroundColor = .contentBkgColor
        self.layer.cornerRadius = 6.0
        self.clipsToBounds = true
        
        self.addSubview(iconImgV)
        self.addSubview(titleLabel)
        self.addSubview(arrowImgV)
        
        iconImgV.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(16)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.height.equalTo(20)
            make.centerY.equalToSuperview()
            make.left.equalTo(iconImgV.snp.right).offset(12)
            make.right.equalTo(arrowImgV.snp.left).offset(-5)
        }
        
        arrowImgV.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-13)
        }
    }
}



class YHCertificateUploadSheetView: UIView {
    
    static let sheetView = YHCertificateUploadSheetView(frame:UIScreen.main.bounds)

    var action:((YHCertificateUploadType)->())?
    
    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    lazy var topView:UIView = {
        let view = UIView()
        view.addSubview(titleLabel)
        view.addSubview(closeBtn)
        
        let line = UIView()
        line.backgroundColor = .separatorColor
        view.addSubview(line)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.left.right.equalToSuperview()
            make.height.equalTo(24)
        }
        closeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.right.equalToSuperview().offset(-20)
            make.width.height.equalTo(24)
        }
        line.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.top.equalTo(titleLabel.snp.bottom).offset(12)
            make.bottom.equalToSuperview()
        }
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_B(ofSize:17)
        label.text = "请选择上传方式"
        return label
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named:"my_cer_sheet_close"), for: .normal)
        btn.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
        return btn
    }()
    
    lazy var tipsLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize:14)
        label.numberOfLines = 0
        label.text = "注意事项：这里是上传应该注意的事项这里是上传应该注意的事项这里是上传应该注意的事项。"
        return label
    }()
    
    lazy var templateView: YHCertificateSampleTemplateView = {
        let view = YHCertificateSampleTemplateView(frame:CGRectZero)
        view.tag = YHCertificateUploadType.sample.rawValue
        let tap = UITapGestureRecognizer(target:self, action:#selector(action(_:)))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var documentPickerVC: UIDocumentPickerViewController = {
        
        let docTypes =   [ "public.image",
                           "com.adobe.pdf",
                           "com.microsoft.word.doc",
                           "org.openxmlformats.wordprocessingml.document",
                           "com.microsoft.powerpoint.ppt",
                           "org.openxmlformats.presentationml.presentation",]

         if #available(iOS 14.0, *) {
             var arr:[UTType] = []
             for docStr in docTypes {
                 if let type = UTType(docStr) {
                     arr.append(type)
                 }
             }
             let docPickerVC = UIDocumentPickerViewController(forOpeningContentTypes: arr)
             docPickerVC.delegate = self
             return docPickerVC
             
         }
         let docPickerVC = UIDocumentPickerViewController(documentTypes: docTypes, in: .open)
         docPickerVC.delegate = self
         return docPickerVC
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    func createUI() {
        
        self.addSubview(blackMaskView)
        self.addSubview(whiteContentView)
        whiteContentView.addSubview(topView)
        whiteContentView.addSubview(templateView)
        whiteContentView.addSubview(tipsLabel)

        let itemView1 = YHCertificateUploadItemView(YHCertificateUploadItem(type:.camera, title:"拍照上传"))
        let itemView2 = YHCertificateUploadItemView(YHCertificateUploadItem(type:.photo, title:"相册上传"))
        let itemView3 = YHCertificateUploadItemView(YHCertificateUploadItem(type:.phoneFile, title:"手机文件上传", subtitle:"从手机文件管理中上传"))
        let itemView4 = YHCertificateUploadItemView(YHCertificateUploadItem(type:.cancel, title:"取消"))
        

        let itemViewArr = [itemView1, itemView2, itemView3, itemView4]
        whiteContentView.addSubviews(itemViewArr)
        
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(16.0, 16.0));
        let layer = CAShapeLayer();
        layer.frame = whiteContentView.bounds;
        layer.path = path.cgPath;
        whiteContentView.layer.mask = layer;
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalToSuperview().offset(355)
        }
        topView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        tipsLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(topView.snp.bottom).offset(20)
        }
        
        templateView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(tipsLabel.snp.bottom).offset(20)
            make.height.equalTo(62.0)
        }

        for (index, itemView) in itemViewArr.enumerated() {
            let tap = UITapGestureRecognizer(target:self, action:#selector(action(_:)))
            itemView.addGestureRecognizer(tap)
            itemView.snp.makeConstraints { make in
                make.left.right.equalToSuperview()
                make.top.equalTo(templateView.snp.bottom).offset(20 + index * 52)
                make.height.equalTo(52.0)
            }
        }
    }
}

extension YHCertificateUploadSheetView  {
    
    func show(_ action:((YHCertificateUploadType)->())?) {
        self.action = action
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func action(_ sender:UITapGestureRecognizer) {
        
        if let targetView = sender.view {
            let tag = targetView.tag
            if let type = YHCertificateUploadType(rawValue:tag), let action = action {
                
                if type == .photo {
                    selectPhoto()
                    
                } else if type == .camera {
                    takePhoto()
                    
                } else if type == .phoneFile {
                    selectFile()
                }
            }
        }
    }
    
}

extension YHCertificateUploadSheetView: (UIImagePickerControllerDelegate & UINavigationControllerDelegate) {
    
    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
    }
    
     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("找不到相机")
        }
    }
    
    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)
        }
    }
    
    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 YHCertificateUploadSheetView: UIDocumentPickerDelegate  {
    
    func selectFile() {
        UIViewController.current?.present(documentPickerVC, animated: true, completion: nil)
    }
    
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let url = urls.first, let fileName = url.lastPathComponent.removingPercentEncoding else {
        
            return
        }
        print("\(url)")
        // 读取文件数据
        // 获取授权
        let fileUrlAuthozied = url.startAccessingSecurityScopedResource()
        if fileUrlAuthozied {
            // 通过文件协调工具来得到新的文件地址，以此得到文件保护功能
            let fileCoordinator = NSFileCoordinator()
            var error: NSError?
            fileCoordinator.coordinate(readingItemAt: url, options:[.forUploading], error: &error) {
                newFileUrl in
                
                if let fileData = try? Data(contentsOf: newFileUrl) {
                    // 将文件数据上传到服务器
                    uploadFile(fileData)
                    dismiss()
                }
            }
            url.stopAccessingSecurityScopedResource()
            if let error = error {
                
            }
        } else {
            print("授权失败")
            dismiss()
        }
    }
    
    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        
    }
    
    func uploadFile(_ data: Data) {

        let format = String(format: "%.2fM", Double(data.count)/(1024.0 * 1024.0))
        print("\(format)")
    }
}
