//
//  YHMySignatureDetailViewController.swift
//  galaxy
//
//  Created by EDY on 2024/3/11.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SafariServices
import IQKeyboardManagerSwift

class YHMySignatureDetailViewController: YHBaseViewController {
    var bottomView: UIView!
    var bottomButton: UIButton!
    var tableView: UITableView!
    var promptView: YHFailPromptView!
    var dataSource: [YHWorkItemListModel]?
    var viewModel: YHMySignatureDetailViewModel!
    var id: Int = 0
    var oldUrl: String?
    var type: Int = 0
    var isSign: Bool = false
    var isAuth: Bool = true // 小程序分享字段
    var orderID: Int = 0
    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 = YHMySignatureDetailViewModel()
        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)
        viewModel.requestSignBack("\(id)") {[weak self] _, _ in
            guard let self = self else { return }
            self.getData()
        }
        viewModel.requestCheckPersonalStatus("\(id)")
        getData()
    }
    
    @objc func getData() {
        viewModel.requestSignatureDetail("\(id)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success {
                let state = self.viewModel.mainModel?.status ?? 0
                // 0-待上传，1-未发送, 2-发送中，3-已发送，4-已签收，5-审核通过，6-驳回
                self.type = state
            } else {
                YHHUD.flash(message: error?.errorMsg ?? "")
            }
            self.checkSign()
        })
    }
    
    func checkSign() {
        viewModel?.requestSignCallBack("\(self.id)", callBackBlock: {[weak self] success, _ in
            guard let self = self else { return }
            self.isSign = success
            let state = self.type
            if state == 0 || state == 1 || state == 2 || state == 3 {
                self.promptView.isHidden = true
                self.bottomButton.isEnabled = true
                self.bottomView.isHidden = false
                self.bottomButton.alpha = 1
                self.bottomButton.setTitle("确定已签章，提交", for: .normal)
                if self.type == 3 && self.viewModel.mainModel?.doc_return_manual.count == 0 && !success {
                    self.bottomButton.isEnabled = false
                    self.bottomButton.alpha = 0.4
                }
            } else if state == 4 {
                self.promptView.isHidden = true
                self.bottomButton.isEnabled = false
                self.bottomView.isHidden = false
                self.bottomButton.alpha = 0.4
                self.bottomButton.setTitle("提交成功", for: .normal)
            } else if state == 5 {
                self.promptView.isHidden = true
                self.bottomView.isHidden = true
                self.bottomButton.isEnabled = true
                self.bottomButton.alpha = 1
                self.bottomButton.setTitle("确定已签章，提交", for: .normal)
            } else {
                self.promptView.isHidden = false
                self.promptView.setPrompt(self.viewModel.mainModel?.audit_opinion ?? "")
                self.bottomButton.isEnabled = true
                self.bottomView.isHidden = false
                self.bottomButton.alpha = 1
                self.bottomButton.setTitle("确定已签章，提交", for: .normal)
                let height = self.getPromptHeight(self.viewModel.mainModel?.audit_opinion ?? "")
                self.promptView.snp.remakeConstraints { make in
                    make.height.equalTo(height)
                    make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
                    make.left.right.equalTo(self.view)
                }
            }
            self.tableView.reloadData()
        })
    }
    
    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: YHDocumentPromptTableViewCell.self)
            tableView.register(cellWithClass: YHSignatureToActionTableViewCell.self)
            tableView.register(cellWithClass: YHSignatureUploadTableViewCell.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)
        }
        
        promptView = {
            let view = YHFailPromptView()
            view.isHidden = true
            return view
        }()
        view.addSubview(promptView)
        promptView.snp.makeConstraints { make in
            make.height.equalTo(35)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.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)") {[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 = YHContentUrl()
                    model.name = fileName
                    model.url = successUrl
                    model.suffix = suffixName
//                    YHHUD.show(.progress(message: "上传中..."))
                    var action = 1
                    if self.oldUrl?.count != 0 {
                        action = 2
                    }
                    self.viewModel.requestFileAction("\(self.id)", action, [successUrl], self.oldUrl ?? "") {[weak self] success, error in
                        guard let self = self else { return }
//                        YHHUD.hide()
                        if success {
                            YHHUD.flash(message: "上传成功")
                        } else {
                            var msg = "上传失败"
                            if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                                msg = errorMsg
                            }
                            YHHUD.flash(message: msg)
                        }
                        self.getData()
                    }
                    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) -> Void)?) {
        // 先OSS上传得到URL
        self.viewModel.uploadImage(img) {
            [weak self] url, _ in
            guard self != nil else { return }
            if let url = url, !url.isEmpty {
                callBack?(true, url)
                return
            }
            callBack?(false, "")
        }
    }
    
    func getMiniPath() -> String {
        var isAuthString = ""
        if isAuth {
            isAuthString = "true"
        } else {
            isAuthString = "false"
        }
        let path = "/serviceHousekeeper/pages/documentEdit/documentEdit?id=\(self.id)&docType=sign&signId=\(self.id)&auth=\(isAuthString)&order_id=\(orderID)&source_from=app"
        return path
    }
    
    deinit {
        removeNotify()
    }
}

extension YHMySignatureDetailViewController: 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: YHDocumentPromptTableViewCell.self)
            cell.type = self.viewModel.mainModel?.doc_type ?? 0
            cell.backgroundColor = .clear
            cell.contentView.backgroundColor = .clear
            return cell
        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHSignatureToActionTableViewCell.self)
            cell.dataSource = self.viewModel.mainModel
            cell.isSign = self.isSign
            cell.miniPath = getMiniPath()
            if self.type == 5 || self.type == 4 {
                cell.isSign = true
            }
            cell.backgroundColor = .clear
            cell.contentView.backgroundColor = .clear
            cell.block = { [weak self] type in
                guard let self = self else { return }
                if type == .sign {
                    if self.isSign {
                        YHHUD.show(.progress(message: ""))
                        self.viewModel.requestSignatureLook("\(self.id)") {[weak self] success, error in
                            YHHUD.hide()
                            guard let self = self else { return }
                            if success {
                                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 ?? "")
                            }
                        }
                    } else {
                        YHHUD.show(.progress(message: ""))
                        self.viewModel.requestSignaturePageURL("\(self.id)", callBackBlock: {[weak self] success, error in
                            YHHUD.hide()
                            guard let self = self else { return }
                            if error?.errorCode == 1008611 {
                                YHCommonAlertView.show("实名认证", "为保证签署有效，请先实名认证", "取消", "去认证") {
                                    self.viewModel.requestSignaturePersonalURL(callBackBlock: {[weak self] _, _ in
                                        guard let self = self else { return }
                                        let url = URL(string: self.viewModel.personalUrl) ?? URL(fileURLWithPath: "")
                                        let safariViewController = SFSafariViewController(url: url)
                                        safariViewController.dismissButtonStyle = .close
                                        safariViewController.delegate = self
                                        safariViewController.modalPresentationStyle = .fullScreen
                                        present(safariViewController, animated: true, completion: nil)
                                    })
                                }
                            } else if error?.errorCode == 1008612 {
                                YHSignAppendStepView.show {[weak self] name, phone in
                                    guard let self = self else { return }
                                    self.viewModel.requestSignaturePersonalWithNameAndPhoneURL(name: name, phone: phone, callBackBlock: {[weak self] _, _ in
                                        guard let self = self else { return }
                                        let url = URL(string: self.viewModel.personalUrl) ?? URL(fileURLWithPath: "")
                                        let safariViewController = SFSafariViewController(url: url)
                                        safariViewController.dismissButtonStyle = .close
                                        safariViewController.delegate = self
                                        safariViewController.modalPresentationStyle = .fullScreen
                                        present(safariViewController, animated: true, completion: nil)
                                    })
                                }
                            } else {
                                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 {
                    YHHUD.show(.progress(message: ""))
                    self.viewModel.requestSignatureLook("\(self.id)") {[weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else { return }
                        if success {
                            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 == .downLoad {
                    // 弹窗 选择发送邮箱
                    let items = [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()
                        }
                    }.show()
                }
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHSignatureUploadTableViewCell.self)
            cell.type = self.type
            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.uploadTypeArr = [ YHCertificateUploadItem(type: .camera, title: "拍照上传"),
                                                YHCertificateUploadItem(type: .photo, title: "相册上传"),
                                                YHCertificateUploadItem(type: .phoneFile, title: "手机文件上传", subtitle: "从手机文件管理中上传"),
                                                YHCertificateUploadItem(type: .wechatUpload, title: "微信上传"),
                                                YHCertificateUploadItem(type: .cancel, title: "取消")]
                    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: [String] = []
                        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 {
                                        successArr.append(url)
                                    } 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)张照片上传失败")
                            }
                            var action = 1
                            if self.oldUrl?.count != 0 {
                                action = 2
                            }
                            // sleep(1) 后端性能问题 不能并发调用接口
                            self.viewModel.requestFileAction("\(self.id)", action, successArr, self.oldUrl ?? "") {[weak self] _, _ in
                                guard let self = self else { return }
                                self.getData()
                            }
                        }
                    }
                    sheetView.wechatUploadBlock = {
                        [weak self] in
                        guard let self = self else { return }
                        let token = YHLoginManager.shared.h5Token
                        var opt_type = 1
                        if let oldUrl = self.oldUrl, !oldUrl.isEmpty {
                            opt_type = 2
                        }
                        let path = "/superApp/pages/wxUpload/wxUpload?param=\(token)&id=\(self.id)&opt_type=\(opt_type)&type=wx_upload_sign_apply&old_url=\(self.oldUrl ?? "")"
                        
                        YHShareManager.shared.openMiniProgram(path: path, title: "微信上传")
                    }
                    sheetView.show()
                }
                
                if type == .reUpload {
                    self.oldUrl = self.viewModel.mainModel?.doc_return_manual[index]
                    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: [String] = []
                        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 {
                                        successArr.append(url)
                                    } 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)张照片上传失败")
                            }
                            var action = 1
                            if self.oldUrl?.count != 0 {
                                action = 2
                            }
                            self.viewModel.requestFileAction("\(self.id)", action, successArr, self.oldUrl ?? "") {[weak self] _, _ in
                                guard let self = self else { return }
                                self.getData()
                            }
                        }
                    }
                    sheetView.show()
                }
                
                if type == .look {
                    YHHUD.show(.progress(message: ""))
                    self.oldUrl = self.viewModel.mainModel?.doc_return_manual[index]
                    self.viewModel.getPublicImageUrl(self.oldUrl ?? "") { success, _ in
                        YHHUD.hide()
                        if let success = success {
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "")
                        }
                    }
                }
                
                if type == .delete {
                    self.oldUrl = self.viewModel.mainModel?.doc_return_manual[index]
                    self.viewModel.requestFileAction("\(self.id)", 3, [], self.oldUrl ?? "") {[weak self] success, error in
                        guard let self = self else { return }
                        if success {
                            YHHUD.flash(message: "删除成功")
                        } else {
                            YHHUD.flash(message: error?.errorMsg ?? "")
                        }
                        self.getData()
                    }
                }
            }
            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?.doc_return_manual.count else { return CGFloat(221) }
            if self.type == 5 {
                return CGFloat(176 + 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 YHMySignatureDetailViewController: SFSafariViewControllerDelegate {
    // MARK: 点击左上角的完成
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true)
        viewModel.requestSignBack("\(id)") {[weak self] _, _ 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 YHMySignatureDetailViewController {
    
    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)
        
//        self.viewModel.requestFileAction("\(self.id)", action, successArr, self.oldUrl ?? "") {[weak self] success, error in
//            guard let self = self else { return }
//            self.getData()
//        }
        
        NotificationCenter.default.addObserver(self, selector: #selector(getData), name: YhConstant.YhNotification.didMySignWeChatFileUploadCallBackNotification, 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()
        }
    }
}
