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

import UIKit
import SafariServices
import IQKeyboardManagerSwift

class YHMyDocumentsDetailViewController: YHBaseViewController {
    
    var stepView: YHStepView!
    var bottomView: UIView!
    var bottomButton: UIButton!
    var tableView: UITableView!
    var promptView: YHFailPromptView!
    var dataSource: [YHWorkItemListModel]?
    var viewModel: YHMyDocumentsDetailViewModel!
    var id: Int = 0
    var oldUrl: String?
    var type: Int = 0
    var isSign: Bool = false
    var isAuth: Bool = true //小程序分享字段
    var fileType: String = "sign"
    var orderID: Int = 0
    
    var isDocDownLoad: Bool = true
    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
    }()
    
    lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHMyDocumentsDetailViewModel()
        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("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)") {[weak self] success, error in
            guard let self = self else { return }
            self.getData()
        }
        viewModel.requestCheckPersonalStatus("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)")
        getData()
    }
    
    func getData() {
        viewModel.requestDocumentsDetail("\(id)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success {
                if self.viewModel.mainModel?.prospectus.id != 0 {
                    self.stepView.snp.remakeConstraints { make in
                        make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                        make.left.right.equalTo(self.view)
                        make.height.equalTo(0)
                    }
                    self.bottomView.isHidden = true
                }
                if self.viewModel.mainModel?.writing_document.status ?? 0 < 6 {
                    //没有doc_sign
                    self.stepView.currentIndex = 0
                    self.bottomView.isHidden = true
                } else {
                    let state = self.viewModel.mainModel?.writing_document.doc_sign.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.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            let state = self.type
            if state < 3 {
                //没有doc_sign
                self.stepView.currentIndex = 0
                self.bottomView.isHidden = true
            }
            else if state == 3  {
                self.promptView.isHidden = true
                self.bottomButton.isEnabled = true
                self.bottomView.isHidden = false
                self.bottomButton.alpha = 1
                self.bottomButton.setTitle("确定已签章，提交", for: .normal)
                self.stepView.currentIndex = 1
                if self.viewModel.mainModel?.writing_document.doc_sign.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.bottomButton.alpha = 0.4
                self.bottomView.isHidden = false
                self.bottomButton.setTitle("提交成功", for: .normal)
                self.stepView.currentIndex = 1
            } 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)
                self.stepView.currentIndex = 1
            } else {
                self.promptView.isHidden = false
                self.promptView.setPrompt(self.viewModel.mainModel?.writing_document.doc_sign.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?.writing_document.doc_sign.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.stepView.currentIndex = 1
            }
            self.isSign = success
            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
        stepView = {
            let step = YHStepView()
            step.dataSource = ["文书稿件", "文书签章"]
            return step
        }()
        view.addSubview(stepView)
        stepView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalTo(view)
            make.height.equalTo(104)
        }
        
        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: YHDocumentMessageTableViewCell.self)
            tableView.register(cellWithClass: YHDocumentPromptTableViewCell.self)
            tableView.register(cellWithClass: YHDocumentToActionTableViewCell.self)
            tableView.register(cellWithClass: YHDocumentUploadTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + YHStepView.height)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.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 self.isDocDownLoad {
                        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                            YHHUD.show(.progress(message: "发送中..."))
                            let params = ["order_id":orderID,"supplement_id":self.viewModel.mainModel?.writing_document.supplement_id ?? 0,"email":text]
                            self.viewModel?.sendEmailForDoc(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 为空")
                        }
                    } else {
                        if let orderID = UserDefaults.standard.value(forKey: "orderIdForPreview") {
                            YHHUD.show(.progress(message: "发送中..."))
                            let params = ["order_id":orderID,"ids":[self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0],"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() {
        YHHUD.show(.progress(message: ""))
        viewModel.requestSignConfirm("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)") {[weak self] success, error in
            guard let self = self else { return }
            YHHUD.hide()
            if success {
                YHHUD.flash(message: "提交成功")
                self.getData()
            } else {
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    YHHUD.flash(message: errorMsg)
                }
            }
        }
    }
    
    func showSureAlert() {
        YHCommonAlertView.show("", "请确认是否已完成编辑并提交", "取消", "确认") {[weak self] in
            guard let self = self else { return }
            YHHUD.show(.progress(message: ""))
            self.viewModel.requestDocumentSubmit("\(self.id)") {[weak self] success, error in
                YHHUD.hide()
                guard let self = self else { return }
                if success {
                    YHHUD.flash(message: "提交成功")
                    self.getData()
//                    self.navigationController?.popViewController()
                }
            }
        }
    }
    
    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
                guard let self = self else { return }
                YHHUD.hide()
                // 再调用业务接口
                if let successUrl = successUrl, !successUrl.isEmpty {
                    var action = 1
                    if self.oldUrl?.count != 0 {
                        action = 2
                    }
                    self.viewModel.requestFileAction("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)", action, [successUrl], self.oldUrl ?? "") {[weak self] success, error in
                        guard let self = self else { return }
                        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)->())?) {
        // 先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, "")
        }
    }
    
    func getMiniPath() -> String {
        var isAuthString = ""
        if isAuth {
            isAuthString = "true"
        } else {
            isAuthString = "false"
        }
        
        let path = "/serviceHousekeeper/pages/documentEdit/documentEdit?id=\(self.id)&docType=doc&signId=\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)&auth=\(isAuthString)&order_id=\(orderID)&source_from=app"
        return path
    }
    
    deinit {
        removeNotify()
    }
}

extension YHMyDocumentsDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if stepView.currentIndex == 0 {
            return 1
        }
        return 3
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if stepView.currentIndex == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHDocumentMessageTableViewCell.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 == .edit {
                    YHHUD.show(.progress(message: ""))
                    self.viewModel.requestDocumentsTemporaryUrl("\(id)", callBackBlock: {[weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else { return }
                        if success {
                            self.viewModel.requestDocumentRecord("\(id)", 2) { success, error in
                            }
                            guard let url = URL(string: self.viewModel?.urlModel?.url) else { return }
                            let tmpVC = SFSafariViewController(url: url)
                            tmpVC.dismissButtonStyle = .close
                            tmpVC.delegate = self
                            tmpVC.modalPresentationStyle = .fullScreen
                            present(tmpVC, animated: true, completion: nil)
                        } else {
                            YHHUD.flash(message: error?.errorMsg ?? "")
                        }
                    })
                }
                
                if type == .submit {
                    self.showSureAlert()
                }
                
                if type == .look {
                    YHHUD.show(.progress(message: ""))
                    self.viewModel.requestDocumentsTemporaryUrl("\(id)", callBackBlock: {[weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else { return }
                        if success {
                            self.viewModel.requestDocumentRecord("\(id)", 1) { success, error in
                            }
                            guard let url = URL(string: self.viewModel?.urlModel?.url) else { return }
                            let tmpVC = SFSafariViewController(url: url)
                            tmpVC.dismissButtonStyle = .close
                            tmpVC.delegate = self
                            tmpVC.modalPresentationStyle = .fullScreen
                            present(tmpVC, 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.enable = false
                        if editType == .sendEmail {
                            isDocDownLoad = true
                            emailInputView.textField.text = ""
                            emailInputView.textField.becomeFirstResponder()
                        }
                    }.show()
//                    YHHUD.show(.progress(message: ""))
//                    self.viewModel.requestDocumentsTemporaryUrl("\(id)", callBackBlock: {[weak self] success, error in
//                        YHHUD.hide()
//                        guard let self = self else { return }
//                        if success {
//                            self.viewModel.requestDocumentRecord("\(id)", 1) { success, error in
//                            }
//                            guard let url = URL(string: self.viewModel?.urlModel?.url) else { return }
//                            let tmpVC = SFSafariViewController(url: url)
//                            tmpVC.dismissButtonStyle = .close
//                            tmpVC.delegate = self
//                            tmpVC.modalPresentationStyle = .fullScreen
//                            present(tmpVC, animated: true, completion: nil)
//                        } else {
//                            YHHUD.flash(message: error?.errorMsg ?? "")
//                        }
//                    })
                }
            }
            return cell
        } else {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withClass: YHDocumentPromptTableViewCell.self)
                cell.type = self.viewModel.mainModel?.writing_document.doc_sign.doc_type ?? 0
                cell.backgroundColor = .clear
                cell.contentView.backgroundColor = .clear
                return cell
            } else if indexPath.row == 1 {
                let cell = tableView.dequeueReusableCell(withClass: YHDocumentToActionTableViewCell.self)
                cell.dataSource = self.viewModel.mainModel
                cell.isSign = self.isSign
                cell.nimiPath = 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 {
                            self.viewModel.requestSignatureLook("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)") {[weak self] success, error in
                                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 {
                            self.viewModel.requestSignaturePageURL("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)", callBackBlock: {[weak self] success, error in
                                guard let self = self else { return }
                                if error?.errorCode == 1008611 {
                                    YHCommonAlertView.show("实名认证", "为保证签署有效，请先实名认证", "取消", "去认证") {
                                        self.viewModel.requestSignaturePersonalURL(callBackBlock: {[weak self] success, error 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] success, error 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.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)") {[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.enable = false
                            if editType == .sendEmail {
                                isDocDownLoad = false
                                emailInputView.textField.text = ""
                                emailInputView.textField.becomeFirstResponder()
                            }
                        }.show()
                    }
                }
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withClass: YHDocumentUploadTableViewCell.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?.writing_document.doc_sign.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:[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.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)", action, successArr, self.oldUrl ?? "") {[weak self] success, error in
                                    guard let self = self else { return }
                                    self.getData()
                                }
                            }
                        }
                        sheetView.show()
                    }
                    
                    if type == .reUpload {
                        self.oldUrl = self.viewModel.mainModel?.writing_document.doc_sign.doc_return_manual[index]
                        let count = self.viewModel.mainModel?.writing_document.doc_sign.doc_return_manual.count ?? 0
                        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: [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.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)", action, successArr, self.oldUrl ?? "") {[weak self] success, error in
                                    guard let self = self else { return }
                                    self.getData()
                                }
                            }
                        }
                        sheetView.show()
                    }
                    
                    if type == .look {
                        YHHUD.show(.progress(message: ""))
                        self.oldUrl = self.viewModel.mainModel?.writing_document.doc_sign.doc_return_manual[index]
                        self.viewModel.getPublicImageUrl(self.oldUrl ?? "") { success, error in
                            YHHUD.hide()
                            if let success = success {
                                self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "")
                            }
                        }
                    }
                    
                    if type == .delete {
//                        YHHUD.flash(message: "产品确定 后续完善")
                        self.oldUrl = self.viewModel.mainModel?.writing_document.doc_sign.doc_return_manual[index]
                        self.viewModel.requestFileAction("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)", 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 stepView.currentIndex == 0 {
            return 190
        } else {
            if indexPath.row == 0 {
                return 104
            } else if indexPath.row == 1 {
                return 180
            } else {
                guard let count = self.viewModel.mainModel?.writing_document.doc_sign.doc_return_manual.count else { return CGFloat(221) }
                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 YHMyDocumentsDetailViewController: SFSafariViewControllerDelegate {
    // MARK: 点击左上角的完成
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true)
        viewModel.requestSignBack("\(self.viewModel.mainModel?.writing_document.doc_sign.id ?? 0)") {[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 YHMyDocumentsDetailViewController {
    
    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.enable = true
            }
            
            self.emailInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}
