//
//  YHGCMySignatureDetailViewController.swift
//  galaxy
//
//  Created by EDY on 2024/12/24.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift
import SafariServices

class YHGCMySignatureDetailViewController: YHBaseViewController {
    var bottomView: UIView!
    var bottomButton: UIButton!
    var tableView: UITableView!
    var dataSource: [YHWorkItemListModel]?
    var viewModel: YHGCMySignatureDetailViewModel!
    var id: Int = 0
    var oldUrl: String?
    var isSign: Bool = false
    var isAuth: Bool = true //小程序分享字段
    var orderID: Int = 0
    var mobile: String = ""
    lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    lazy var blackMaskView: UIView = {
        let view = UIView(frame:UIScreen.main.bounds)
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissed))
        view.addGestureRecognizer(tap)
        view.isHidden = true
        return view
    }()
    
    lazy var emailInputView: YHEmailInputAlertView = {
        let view = YHEmailInputAlertView.emailInputView(defalutText: "请输入邮箱")
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHGCMySignatureDetailViewModel()
        gk_navTitle = "文书操作"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1
        setView()
        getData()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
    }
    
    func getData() {
        viewModel.requestSignatureDetail("\(id)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success {
                let state = self.viewModel.mainModel?.docStatus ?? 0
                // 1000 1001 1002 1003-待签署; 1004-已签署; 1005-待审核; 1006-已驳回; 1007-已完成

                if state == 1000 || state == 1001 || state == 1002 || state == 1003 {
                    self.bottomButton.isEnabled = true
                    self.bottomView.isHidden = false
                    self.bottomButton.alpha = 1
                    if self.viewModel.mainModel?.docType == 1001 {
                        self.bottomButton.setTitle("确定已签章，提交", for: .normal)
                    } else {
                        self.bottomButton.setTitle("确定已签署，提交", for: .normal)
                    }
                } else if state == 1007 {
                    self.bottomView.isHidden = true
                    self.bottomButton.isEnabled = true
                    self.bottomButton.alpha = 1
                } else if state == 1006 || state == 1004 || state == 1005 {
                    self.bottomView.isHidden = true
                    self.bottomButton.isEnabled = true
                    self.bottomButton.alpha = 1
                }
                self.tableView.reloadData()
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "")
            }
        })
    }
    
    func getPromptHeight(_ value: String) -> CGFloat {
        let text = "驳回原因：" + value // 要显示的文本内容
        let font = UIFont.PFSC_R(ofSize: 12) // 字体大小
        let maxWidth = KScreenWidth - 74 // 最大宽度限制
        
        // 创建NSAttributedString对象并设置属性
        let attributes = [NSAttributedString.Key.font : font] as [NSAttributedString.Key : Any]
        _ = NSMutableAttributedString(string: text, attributes: attributes)
         
        // 根据指定的最大宽度和字体大小计算文本的高度
        let size = (text as NSString).boundingRect(with: CGSize(width: maxWidth, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size
        return size.height + 15
    }
    
    func updateDataSource() {
        self.tableView.reloadData()
    }
    
    func setView() {
        addKeyBoardNotify()

        view.backgroundColor = .contentBkgColor
        tableView = {
            let tableView = UITableView(frame:.zero, style:.grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHGCDocumentPromptTableViewCell.self)
            tableView.register(cellWithClass: YHGCSignatureToActionTableViewCell.self)
            tableView.register(cellWithClass: YHGCSignatureUploadTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.bottom.equalTo(view)
        }
        
        bottomView = {
            let bottom = UIView()
            bottom.backgroundColor = .white
            bottom.isHidden = true
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        
        bottomButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("确定已签章，提交", for: .normal)
            button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.clipsToBounds = true
            button.alpha = 0
            button.addTarget(self, action: #selector(submit), for: .touchUpInside)
            return button
        }()
        bottomView.addSubview(bottomButton)
        bottomButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
            make.left.equalTo(16)
        }
        view.addSubview(blackMaskView)
        view.addSubview(emailInputView)
        emailInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHEmailInputAlertView.height)
            make.bottom.equalToSuperview().offset(YHEmailInputAlertView.height)
        }
        
        emailInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            
            if let text = text {
                YHCheckEamilAlertView.show(nil,text, "取消", "确认") {
                    //进行
                    //发送接口
                    if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                        YHHUD.show(.progress(message: "发送中..."))
                        let params = ["order_id":orderID,"ids":[self.id],"email":text]
                        self.viewModel?.sendEmailForDocs(params, callBackBlock: { success, error in
                            YHHUD.hide()
                            if success {
                                YHHUD.flash(message: "已发送至邮箱")
                            } else {
                                let msg = error?.errorMsg ?? "发送失败"
                                YHHUD.flash(message: msg)
                            }
                        })
                    } else {
                        YHHUD.flash(message: "订单ID 为空")
                    }
                }
            }
        }
        bottomButton.layoutIfNeeded()
        bottomButton.addYinHeGradualLayer()
    }
    
    @objc func dismissed() {
        emailInputView.textField.resignFirstResponder()
    }
    
    @objc func submit() {
        viewModel.requestSignConfirm("\(self.id)", orderID: orderID) {[weak self] success, error in
            guard let self = self else { return }
            if success {
                self.getData()
                YHHUD.flash(message: "提交成功")
            } else {
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
    
    func uploadFile(_ fileUrl:URL) {
        if let fileData = try? Data(contentsOf: fileUrl) {
            // 将文件数据上传到服务器
            let size = String(format: "%.2fM", Double(fileData.count)/(1024.0 * 1024.0))
//            print("\(size)")
            // 先OSS上传得到URL
            YHHUD.show(.progress(message: "上传中..."))
            self.viewModel.uploadFile(fileUrl.absoluteString) {
                [weak self] successUrl, error in
                
                YHHUD.hide()
                
                guard let self = self else { return }
                
                // 再调用业务接口
                if let successUrl = successUrl, !successUrl.isEmpty {
                    var fileName = fileUrl.lastPathComponent
                    if fileName.isEmpty {
                        fileName = successUrl.lastPathComponent
                    }
                    let suffixName = successUrl.pathExtension.lowercased()
                    let model = YHMySignedDocumentModel()
                    model.fileName = fileName
                    model.name = fileName
                    model.fileUrl = successUrl
                    model.url = successUrl
                    self.viewModel.mainModel?.signedDocument.append(model)
                    self.tableView.reloadData()
                    return
                }
                var msg = "上传图片失败"
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    msg = errorMsg
                }
                YHHUD.flash(message: msg)
            }
        } else {
            YHHUD.flash(message: "识别文件失败")
        }
    }
    
    func uploadImage(_ img: UIImage, imageName:String, callBack:((Bool, String)->())?) {
        // 先OSS上传得到URL
        self.viewModel.uploadImage(img) {
            [weak self] url, error in
            guard self != nil else { return }
            if let url = url, !url.isEmpty {
                callBack?(true, url)
                return
            }
            callBack?(false, "")
        }
    }
    
    private func downloadRemoteFile(url: URL, completiton: @escaping (_ destination: URL?) -> Void) {
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        DispatchQueue.main.async {
            YHHUD.show(.progress(message: "加载文件中..."))
        }
        let task = session.downloadTask(with: url) { (tempLocalUrl, response, error) in
            DispatchQueue.main.async {
                YHHUD.hide()
            }
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // 下载完成，尝试打开文件
                let fileManager = FileManager.default
                let destination = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(response?.suggestedFilename ?? UUID().uuidString)
                do {
                    if fileManager.fileExists(atPath: destination.path) {
                        try fileManager.removeItem(at: destination)
                    }
                    try fileManager.moveItem(at: tempLocalUrl, to: destination)
                    completiton(destination)
                } catch {
                    completiton(nil)
                    DispatchQueue.main.async {
                        YHHUD.flash(message: "下载文件失败")
                    }
                }
            } else {
                completiton(nil)
                DispatchQueue.main.async {
                    YHHUD.flash(message: "下载文件失败")
                }
            }
        }
        task.resume()
    }
    
    deinit {
        removeNotify()
    }
}

extension YHGCMySignatureDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHGCDocumentPromptTableViewCell.self)
            cell.type = self.viewModel.mainModel
            cell.backgroundColor = .clear
            cell.contentView.backgroundColor = .clear
            return cell
        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHGCSignatureToActionTableViewCell.self)
            cell.dataSource = self.viewModel.mainModel
            cell.backgroundColor = .clear
            cell.contentView.backgroundColor = .clear
            cell.block = { [weak self] type in
                guard let self = self else { return }
                if type == .sign {
                 
                    YHHUD.show(.progress(message: ""))
                    self.viewModel.requestSignaturePageURL("\(self.id)", callBackBlock: {[weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else { return }
                        if success ?? false {
                            let url = URL(string: self.viewModel.pageUrl) ?? URL(fileURLWithPath: "")
                            let safariViewController = SFSafariViewController(url: url)
                            safariViewController.dismissButtonStyle = .close
                            safariViewController.delegate = self
                            safariViewController.modalPresentationStyle = .fullScreen
                            present(safariViewController, animated: true, completion: nil)
                        } else {
                            YHHUD.flash(message: error?.errorMsg ?? "")
                        }
                    })
                }
                
                if type == .look {
                    if self.viewModel.mainModel?.docStatus == 1002 {
                        YHCommonAlertView.show("", "文书编写中，请稍候查看", "", "我知道了") {
                            
                        }  
                    } else {
                        if self.viewModel.mainModel?.commonFile.count != 0 {
                            self.viewModel.getPublicImageUrl(self.viewModel.mainModel?.commonFile ?? "") { success, error in
                                if let success = success {
                                    self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "")
                                }
                            }
                        } else {
                            YHHUD.flash(message: "文书编写中，请稍候查看")
                        }
                    }
                }
                
                if type == .downLoad {
                    //弹窗 选择发送邮箱
                    let items = [YHCertificateEditItem(type:.sendToWechat, title:"分享至微信"),
                                 YHCertificateEditItem(type:.sendEmail, title:"发送至邮箱"),
                                 YHCertificateEditItem(type:.cancel, title:"取消")]
                    YHCertificateEditSheetView.sheetView(items:items,sheetTitle: "请选择下载方式") {
                        [weak self] editType in
                        guard let self = self else { return }
                        
                        IQKeyboardManager.shared.isEnabled = false
                        if editType == .sendEmail {
                            emailInputView.textField.text = ""
                            emailInputView.textField.becomeFirstResponder()
                        }
                        if editType == .sendToWechat {
                            if self.viewModel.mainModel?.commonFile.count == 0 {
                                YHHUD.flash(message: "文件生成中")
                                return
                            }
                            self.viewModel.getPublicImageUrl(self.viewModel.mainModel?.commonFile ?? "") { [weak self] success, error in
                                YHHUD.hide()
                                guard let self = self else {
                                    return
                                }
                                if let success = success, let url = URL(string: success) {
                                    //self.previewFile(url)
                                    //YHShareManager.shared.sendLinkContent(self.name, "", UIImage(), link: success)
                                    self.downloadRemoteFile(url: url) { [weak self] destination in
                                        guard let self = self else {
                                            return
                                        }
                                        if let destination = destination,  !destination.absoluteString.isEmpty {
                                            var name = ""
                                            if self.viewModel.mainModel?.docType == 1000 {
                                                name = "代理委托书"
                                            } else if self.viewModel.mainModel?.docType == 1001 {
                                                name = "赴港同意书"
                                            } else if self.viewModel.mainModel?.docType == 1002 {
                                                name = "声明书"
                                            }
                                            DispatchQueue.main.async {
                                                YHShareManager.shared.shareFileToWeChat(fileUrl: destination, filename: name + "." + destination.pathExtension.lowercased(), ext: destination.pathExtension.lowercased())
                                            }
                                        }
                                    }
                                } else {
                                    var errorMsg = "文书正在生成中，请稍后再试"
                                    if let error = error, error.errorMsg.count > 0 {
                                        errorMsg = error.errorMsg
                                    }
                                    YHHUD.flash(message: errorMsg)
                                }
                            }
                        }
                    }.show()
                }
                
                if type == .add {
                    //跳转补充详情
                    let vc = YHGCSignatureAddViewController()
                    vc.orderID = orderID
                    self.navigationController?.pushViewController(vc)
                }
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHGCSignatureUploadTableViewCell.self)
            cell.dataSource = self.viewModel.mainModel
            cell.backgroundColor = .clear
            cell.contentView.backgroundColor = .clear
            cell.block = { [weak self] type, index in
                guard let self = self else { return }
                if type == .upload {
                    self.oldUrl = ""
                    let count = self.viewModel.mainModel?.doc_return_manual.count ?? 0
                    if count >= 10 {
                        YHHUD.flash(message: "最多上传10个图片或文件")
                        return
                    }
                    var maxCount = 10 - count
                    if maxCount > 9 {
                        maxCount = 9
                    }
                    let sheetView = YHDocumentUploadView.sheetView()
                    sheetView.maxSelectCount = maxCount
                    sheetView.uploadFilesBlock = {
                        [weak self] fileUrl in
                        guard let self = self else { return }
                        print(fileUrl)
                        uploadFile(fileUrl)
                    }
                    sheetView.uploadImageBlock = {
                        [weak self] imgArr in
                        guard let self = self else { return }
                        let group = DispatchGroup()
                        var successArr:[YHMySignedDocumentModel] = []
                        var failArr:[YHSelectImageItem] = []

                        YHHUD.show(.progress(message: "上传中..."))
                        for item in imgArr {
                            if let image = item.data {
                                group.enter()
                                uploadImage(image, imageName:item.name) {
                                    success, url  in
                                    if success {
                                        let model = YHMySignedDocumentModel()
                                        model.fileUrl = url
                                        model.fileName = item.name
                                        model.name = item.name
                                        model.url = url
                                        successArr.append(model)
                                    } else {
                                        failArr.append(item)
                                    }
                                    group.leave()
                                }
                            }
                        }
                        
                        // 等待所有任务完成
                        group.notify(queue: .main) {
                            YHHUD.hide()
                            // 所有任务完成，回到主线程继续执行
                            print("所有任务完成")
                            if imgArr.count == successArr.count {
                                YHHUD.flash(message: "上传成功")
                            } else {
                                YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
                            }
                            for item in successArr {
                                self.viewModel.mainModel?.signedDocument.append(item)
                            }
                            self.tableView.reloadData()
                        }
                    }
                    sheetView.show()
                }
                
                if type == .reUpload {
                    let count = self.viewModel.mainModel?.doc_return_manual.count ?? 0
                    var maxCount = 10 - count
                    if maxCount > 9 {
                        maxCount = 9
                    }
                    let sheetView = YHDocumentUploadView.sheetView()
                    sheetView.maxSelectCount = 9
                    sheetView.uploadFilesBlock = {
                        [weak self] fileUrl in
                        guard let self = self else { return }
                        print(fileUrl)
                        uploadFile(fileUrl)
                    }
                    sheetView.uploadImageBlock = {
                        [weak self] imgArr in
                        guard let self = self else { return }
                        let group = DispatchGroup()
                        var successArr:[YHMySignedDocumentModel] = []
                        var failArr:[YHSelectImageItem] = []

                        YHHUD.show(.progress(message: "上传中..."))
                        for item in imgArr {
                            if let image = item.data {
                                group.enter()
                                uploadImage(image, imageName:item.name) {
                                    success, url  in
                                    if success {
                                        let model = YHMySignedDocumentModel()
                                        model.fileUrl = url
                                        model.fileName = item.name
                                        model.name = item.name
                                        model.url = url
                                        successArr.append(model)
                                    } else {
                                        failArr.append(item)
                                    }
                                    group.leave()
                                }
                            }
                        }
                        
                        // 等待所有任务完成
                        group.notify(queue: .main) {
                            YHHUD.hide()
                            // 所有任务完成，回到主线程继续执行
                            print("所有任务完成")
                            if imgArr.count == successArr.count {
                                YHHUD.flash(message: "上传成功")
                            } else {
                                YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
                            }
                            self.viewModel.mainModel?.signedDocument.remove(at: index)
                            for item in successArr {
                                self.viewModel.mainModel?.signedDocument.append(item)
                            }
                            self.tableView.reloadData()
                        }
                    }
                    sheetView.show()
                }
                
                if type == .look {
                    YHHUD.show(.progress(message: ""))
                    self.oldUrl = self.viewModel.mainModel?.signedDocument[index].url
                    self.viewModel.getPublicImageUrl(self.oldUrl ?? "") { success, error in
                        YHHUD.hide()
                        if let success = success {
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "")
                        }
                    }
                }
                
                if type == .delete {
                    self.viewModel.mainModel?.signedDocument.remove(at: index)
                    self.tableView.reloadData()
                }
                
                if type == .downLoad {
                    //弹窗 选择发送邮箱
                    let items = [YHCertificateEditItem(type:.sendToWechat, title:"分享至微信"),
                                 YHCertificateEditItem(type:.sendEmail, title:"发送至邮箱"),
                                 YHCertificateEditItem(type:.cancel, title:"取消")]
                    YHCertificateEditSheetView.sheetView(items:items,sheetTitle: "请选择下载方式") {
                        [weak self] editType in
                        guard let self = self else { return }
                        
                        IQKeyboardManager.shared.isEnabled = false
                        if editType == .sendEmail {
                            emailInputView.textField.text = ""
                            emailInputView.textField.becomeFirstResponder()
                        }
                        if editType == .sendToWechat {
                            if self.viewModel.mainModel?.commonFile.count == 0 {
                                YHHUD.flash(message: "文件生成中")
                                return
                            }
                            self.viewModel.getPublicImageUrl(self.viewModel.mainModel?.commonFile ?? "") { [weak self] success, error in
                                YHHUD.hide()
                                guard let self = self else {
                                    return
                                }
                                if let success = success, let url = URL(string: success) {
                                    //self.previewFile(url)
                                    //YHShareManager.shared.sendLinkContent(self.name, "", UIImage(), link: success)
                                    self.downloadRemoteFile(url: url) { [weak self] destination in
                                        guard let self = self else {
                                            return
                                        }
                                        if let destination = destination,  !destination.absoluteString.isEmpty {
                                            var name = ""
                                            if self.viewModel.mainModel?.docType == 1000 {
                                                name = "代理委托书"
                                            } else if self.viewModel.mainModel?.docType == 1001 {
                                                name = "赴港同意书"
                                            } else if self.viewModel.mainModel?.docType == 1002 {
                                                name = "声明书"
                                            }
                                            DispatchQueue.main.async {
                                                YHShareManager.shared.shareFileToWeChat(fileUrl: destination, filename: name + "." + destination.pathExtension.lowercased(), ext: destination.pathExtension.lowercased())
                                            }
                                        }
                                    }
                                } else {
                                    var errorMsg = "文书正在生成中，请稍后再试"
                                    if let error = error, error.errorMsg.count > 0 {
                                        errorMsg = error.errorMsg
                                    }
                                    YHHUD.flash(message: errorMsg)
                                }
                            }
                        }
                    }.show()
                }
            }
            return cell
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 104
        } else if indexPath.row == 1 {
            return 180
        } else {
            guard let count = self.viewModel.mainModel?.signedDocument.count else { return CGFloat(221) }
            if self.viewModel.mainModel?.docStatus == 1007 || self.viewModel.mainModel?.docStatus == 1006 || self.viewModel.mainModel?.docStatus == 1004 || self.viewModel.mainModel?.docStatus == 1005 {
                return CGFloat(168 + count * 71)
            } else {
                return CGFloat(221 + count * 71)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 7
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

extension YHGCMySignatureDetailViewController: SFSafariViewControllerDelegate {
    // MARK: 点击左上角的完成
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true)
        viewModel.requestSignBack("\(id)") {[weak self] success, error in
            guard let self = self else { return }
            self.getData()
        }
    }

    // MARK: 加载完成
    func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
        print(#function)
    }
    
    // MARK: 点击右下角调用Safari浏览器打开
    func safariViewControllerWillOpenInBrowser(_ controller: SFSafariViewController) {
        print(#function)
    }
}


extension YHGCMySignatureDetailViewController {
    
    func addKeyBoardNotify() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func removeNotify() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if notification.userInfo != nil {
            
            guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {return }
            
            let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
            self.blackMaskView.isHidden = !isKeyboardShow
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileRenameInputView.height)
            
            if !isKeyboardShow {
                IQKeyboardManager.shared.isEnabled = true
            }
            
            self.emailInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}

