//
//  YHResignDocumentDetailViewController.swift
//  galaxy
//
//  Created by alexzzw on 2024/9/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SafariServices
import AttributedString
import IQKeyboardManagerSwift

class YHResignDocumentDetailViewController: YHBaseViewController {
    
    private var editEvent: (() -> Void)?
    private var submitEvent: (() -> Void)?
    private var signatureConfirmationEvent: (() -> Void)?
    private var previewEvent: (() -> Void)?
    private var infoConfirmationEvent: (() -> Void)?
    private var downloadEvent: (() -> Void)?

    enum RowType {
        case tips(_ title: String, _ detail: ASAttributedString)
        case content(_ title: String, _ fileName: String, _ status: YHResignDocumentStatus, _ config: YHResignDocumentStatusCell.ButtonsConfig)
        case uploadHeader(_ title: String)
        case uploadFile(_ title: String, _ url: String, _ editTypes: [YHCertificateEditType])
        case uploadAction(_ uploadName: String, _ isUploadButtonEnable: Bool = false, _ isSureButtonEnable: Bool = false, _ topMargin: CGFloat = 16)
    }
    
    private var datas: [[RowType]] = []
    private lazy var viewModel = YHResignDocumentViewModel()
    private var detailModel: YHResignDocumentCompleteModel?
    
    // 进签字再出来就要显示loading
    private var isNeedShowLoading: Bool = true
    private let docId: Int
    private var name: String
    private let uploadMaxCount = 10
        
    init(_ docId: Int, _ name: String = "") {
        self.docId = docId
        self.name = name
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var tableView: UITableView = {
        let view = UITableView(frame:.zero, style:.grouped)
        view.estimatedSectionHeaderHeight = 16.0
        view.estimatedSectionFooterHeight = 0.01
        view.sectionHeaderHeight = 16.0
        view.sectionFooterHeight = 0.01
        view.contentInsetAdjustmentBehavior = .never
        view.showsVerticalScrollIndicator = false
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.tableFooterView = UITableViewHeaderFooterView()
        view.rowHeight = UITableView.automaticDimension
        view.register(YHResignDocumentTipsCell.self, forCellReuseIdentifier: YHResignDocumentTipsCell.cellReuseIdentifier)
        view.register(YHResignDocumentStatusCell.self, forCellReuseIdentifier: YHResignDocumentStatusCell.cellReuseIdentifier)
        
        view.register(YHResignDocumentUploadHeaderCell.self, forCellReuseIdentifier: YHResignDocumentUploadHeaderCell.cellReuseIdentifier)
        view.register(YHResignDocumentUploadFileCell.self, forCellReuseIdentifier: YHResignDocumentUploadFileCell.cellReuseIdentifier)
        view.register(YHResignDocumentUploadActionCell.self, forCellReuseIdentifier: YHResignDocumentUploadActionCell.cellReuseIdentifier)
        return view
    }()
    
    private 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
    }()
    
    private lazy var emailInputView: YHEmailInputAlertView = {
        let view = YHEmailInputAlertView.emailInputView(defalutText: "请输入邮箱")
        view.editBlock = { [weak self] text in
            guard let self = self else { return }
            guard let text = text else { return }
            YHCheckEamilAlertView.show(nil, text, "取消", "确认") { [weak self] in
                //发送接口
                guard let self = self else {
                    return
                }
                YHHUD.show(.progress(message: "发送中..."))
                self.viewModel.sendOriginalDoc(self.docId, text) { success, error in
                    YHHUD.hide()
                    if success {
                        YHHUD.flash(message: "已发送至邮箱")
                    } else {
                        let msg = error?.errorMsg ?? "发送失败"
                        YHHUD.flash(message: msg)
                    }
                }
            }
        }
        return view
    }()
    
    private lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        addKeyBoardNotify()
        tableView.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let needLoading = isNeedShowLoading
        isNeedShowLoading = false
        requestData(isNeedLoading: needLoading)
    }
    
    deinit {
        removeNotify()
    }
}

extension YHResignDocumentDetailViewController {
    private func setupUI() {
        gk_navTitle = name
        gk_navBarAlpha = 1.0
        gk_navBackgroundColor = .white
        
        view.backgroundColor = UIColor.contentBkgColor
        view.addSubview(tableView)
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalToSuperview()
        }
        
        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)
        }
    }
    
    private func requestData(isNeedLoading: Bool = false) {
        if isNeedLoading {
            YHHUD.show(.progress(message: "加载中..."))
        }
        viewModel.getDocumentDetail(docId: docId) { [weak self] documentModel, error in
            self?.detailModel = documentModel
            if isNeedLoading {
                YHHUD.hide()
            }
            guard let documentModel = documentModel else {
                printLog("YHResignDocumentDetailViewController:  请求失败")
                if let errorMsg = error?.errorMsg, errorMsg.count > 0 {
                    YHHUD.flash(message: errorMsg)
                }
                return
            }
            guard let self = self else {
                return
            }
            var firstSetcion: [RowType] = []
            var secondSetcion: [RowType] = []
            if let docType = YHResignDocumentType(rawValue: documentModel.docType), let status = YHResignDocumentStatus.getStatus(documentModel.docStatus) {
                firstSetcion.append(.tips("​填写指引", docType.attributedTips()))
                let config = self.getStatusButtonsConfig(docType: docType, status: status, model: documentModel)
                secondSetcion = [.content("文书稿件", self.name, status, config)]
                datas.removeAll()
                datas.append(firstSetcion)
                datas.append(secondSetcion)
                let uploadSection = getUploadSection(status: status, model: documentModel)
                if uploadSection.count > 0 {
                    datas.append(uploadSection)
                }
                tableView.reloadData()
            }
        }
    }
}

extension YHResignDocumentDetailViewController {
    
    @objc private func dismissed() {
        emailInputView.textField.resignFirstResponder()
    }
    
    private 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)
    }
    
    private func removeNotify() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc private 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
            blackMaskView.isHidden = !isKeyboardShow
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileRenameInputView.height)
            
            if !isKeyboardShow {
                IQKeyboardManager.shared.enable = true
            }
            
            emailInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            view.setNeedsLayout()
            view.layoutIfNeeded()
        }
    }
    
    private func previewFile(_ url: URL) {
        let safariViewController = SFSafariViewController(url: url)
        safariViewController.dismissButtonStyle = .close
        safariViewController.modalPresentationStyle = .fullScreen
        present(safariViewController, animated: true, completion: nil)
    }
}

extension YHResignDocumentDetailViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        datas.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        guard datas.count > section else {
            return 0
        }
        return datas[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard datas.count > indexPath.section else {
            return UITableViewCell()
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return UITableViewCell()
        }
        let item = sectionArr[indexPath.row]
        
        switch item {
        case let .tips(title, detail):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentTipsCell.cellReuseIdentifier) as? YHResignDocumentTipsCell {
                cell.setupCellASAttributedInfo(title: title, detail: detail)
                return cell
            }
        case let .content(title, fileName, status, config):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentStatusCell.cellReuseIdentifier) as? YHResignDocumentStatusCell {
                cell.setupCellInfo(title: title, fileName: fileName, status: status, buttonsConfig: config)
                return cell
            }
        case let .uploadHeader(title):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentUploadHeaderCell.cellReuseIdentifier) as? YHResignDocumentUploadHeaderCell {
                cell.setupCellInfo(title)
                return cell
            }
        case let .uploadFile(title, urlStr, editTypes):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentUploadFileCell.cellReuseIdentifier) as? YHResignDocumentUploadFileCell {
                let cellType: YHResignRoundCellType = sectionArr.count - 1 == indexPath.row ? .bottom : .mid
                cell.setupCellInfo(title, cellType: cellType)
                cell.editButtonClickEvent = { [weak self] in
                    guard let self = self else { return }
                    let items: [YHCertificateEditItem] = editTypes.map {
                        YHCertificateEditItem(type: $0, title: $0.editName())
                    }
                    YHCertificateEditSheetView.sheetView(items:items) { [weak self] editType in
                        guard let self = self else { return }
                        if editType == .reupload {
                            //
                        } else if editType == .delete { // 删除
                            //
                        } else if editType == .preview { // 预览
                            guard URL(string: urlStr) != nil else {
                                return
                            }
                            YHHUD.show(.progress(message: ""))
                            self.viewModel.getPublicImageUrl(urlStr) { [weak self] success, error in
                                guard let self = self else { return }
                                YHHUD.hide()
                                if let success = success {
                                    self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "")
                                }
                            }
                        }
                    }.show()
                }
                return cell
            }
        case let .uploadAction(uploadName, isUploadButtonEnable, isSureButtonEnable, topMargin):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentUploadActionCell.cellReuseIdentifier) as? YHResignDocumentUploadActionCell {
                cell.setupCellInfo(uploadName: uploadName, isUploadButtonEnable: isUploadButtonEnable, isSureButtonEnable: isSureButtonEnable, topMargin: topMargin)
                cell.uploadButtonClickEvent = { [weak self] in
                    guard let self = self else {
                        return
                    }
                    guard let detailModel = self.detailModel else {
                        return
                    }
                    let count = detailModel.signedDocument.count
                    if count >= 10 {
                        YHHUD.flash(message: "最多上传10个图片或文件")
                        return
                    }
                    let allowedCount = 10 - count
                    let sheetView = YHDocumentUploadView.sheetView()
                    sheetView.maxSelectCount = allowedCount
                    sheetView.uploadFilesBlock = { [weak self] fileUrl in
                        guard let self = self else { return }
                        printLog(fileUrl)
                        self.uploadFile(fileUrl)
                    }
                    sheetView.uploadImageBlock = { [weak self] imgArr in
                        guard let self = self else { return }
                        self.uploadImages(imgArr: imgArr)
                    }
                    sheetView.show()
                }
                cell.sureButtonClickEvent = { [weak self] in
                    guard let self = self else { return }
                    self.submitAllUploadFiles()
                }
                return cell
            }
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
}

extension YHResignDocumentDetailViewController {
    
    private func updateButtonEvent(model: YHResignDocumentCompleteModel) {
        editEvent = { [weak self] in
            guard let self = self else {
                return
            }
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.getResginDocumentUrl(docId: model.docId, isEditable: true) { [weak self] model, error in
                YHHUD.hide()
                guard let self = self else {
                    return
                }
                if let urlString = model?.url, let url = URL(string: urlString) {
                    self.previewFile(url)
                } else if let error = error {
                    let errorMsg = error.errorMsg
                    YHHUD.flash(message: errorMsg)
                }
            }
            printLog("###editEvent")
        }
        
        submitEvent = { [weak self] in
            guard let self = self else {
                return
            }
            // 产品说增加二次弹窗确认
            YHCommonAlertView.show("", "确认提交？", "取消", "确认", fullGuestureEnable: false) {
            } callBack: { [weak self] in
                guard let self = self else {
                    return
                }
                YHHUD.show(.progress(message: "加载中..."))
                self.viewModel.submitResginDocument(model.docId, nil) { success, error in
                    YHHUD.hide()
                    if success {
                        YHHUD.flash(message: "提交成功")
                        self.requestData(isNeedLoading: true)
                    } else if let error = error {
                        let errorMsg = error.errorMsg
                        YHHUD.flash(message: errorMsg)
                    }
                }
            }
            
            printLog("###submitEvent")
        }
        
        signatureConfirmationEvent = { [weak self] in
            guard let self = self else {
                return
            }
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.resginDocumentSignature(model.docId, nil) { [weak self] signatureModel, error in
                YHHUD.hide()
                guard let self = self else {
                    return
                }
                guard let signatureModel = signatureModel else {
                    if let error = error {
                        printLog("###续期文书签字: \(error.errorMsg)")
                        let errorMsg = error.errorMsg
                        YHHUD.flash(message: errorMsg)
                    }
                    return
                }
                self.isNeedShowLoading = true
                let url = signatureModel.url
                // 跳签字
                let vc = YHSignatureWebViewController()
                vc.titleName = self.name
                vc.realNameUrl = url
                self.navigationController?.pushViewController(vc)
            }
        }
        
        previewEvent = { [weak self] in
            guard let self = self else {
                return
            }
            YHHUD.show(.progress(message: "加载中..."))
            self.viewModel.previewResginDocument(docId: model.docId) { [weak self] model, error in
                YHHUD.hide()
                guard let self = self else {
                    return
                }
                // 全部是私域链接，转公域处理
                if let urlString = model?.url {
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.getPublicImageUrl(urlString) { success, error in
                        YHHUD.hide()
                        if let success = success, let url = URL(string: success) {
                            self.previewFile(url)
                        } else if let error = error {
                            let errorMsg = error.errorMsg
                            YHHUD.flash(message: errorMsg)
                        }
                    }
                } else if let error = error {
                    let errorMsg = error.errorMsg
                    YHHUD.flash(message: errorMsg)
                }
            }
            printLog("###previewEvent")
        }
        
        infoConfirmationEvent = { [weak self] in
            guard let self = self else {
                return
            }
            
            printLog("跳转QMAS")
            if let param = YHLoginManager.shared.userModel?.token, param.count > 5 {
                printLog(param)
                var url = YHBaseUrlManager.shared.curH5URL() + "superAppBridge.html#/guide/qmas"
                //https://test-hkdiy-h5.galaxy-immi.com/superAppBridge.html#/guide/qmas?token=xx&doc_id=xx
                url = url + "?param=" + YHLoginManager.shared.h5Token + "&doc_id=\(model.docId)"
                let vc = YHH5WebViewVC()
                vc.isFullScreenFlag = false
                vc.navTitle = "QMAS文件信息确认" //self.name
                vc.url = url
                self.navigationController?.pushViewController(vc)
            }
        }
        
        downloadEvent = { [weak self] in
            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 {
                    self.emailInputView.textField.text = ""
                    self.emailInputView.textField.becomeFirstResponder()
                }
            }.show()
        }
    }
    
    private func getUploadSection(status: YHResignDocumentStatus,  model: YHResignDocumentCompleteModel) -> [RowType] {
        var uploadSection: [RowType] = []
        if status == .pendingConfirmation {
            uploadSection.append(.uploadHeader("上传已签署件"))
            model.signedDocument.forEach {
                uploadSection.append(.uploadFile($0.fileName, $0.url, [.preview, .reupload, .delete, .cancel]))
            }
            var name = "上传已签署件"
            var isUploadEnable = true
            let isSureButtonEnable = model.signedDocument.count > 0
            if model.signedDocument.count == uploadMaxCount {
                name = "继续上传"
                isUploadEnable = false
            } else if model.signedDocument.count > 0 {
                name = "继续上传"
                isUploadEnable = true
            }
            uploadSection.append(.uploadAction(name, isUploadEnable, isSureButtonEnable, isSureButtonEnable ? 4 : 16))
        } else {
            if model.signedDocument.count > 0 {
                uploadSection.append(.uploadHeader("上传已签署件"))
                model.signedDocument.forEach {
                    uploadSection.append(.uploadFile($0.fileName, $0.url, [.preview, .cancel]))
                }
            }
        }
        return uploadSection
    }
    
    private func getStatusButtonsConfig(docType: YHResignDocumentType, status: YHResignDocumentStatus,  model: YHResignDocumentCompleteModel) -> YHResignDocumentStatusCell.ButtonsConfig {
        var config = YHResignDocumentStatusCell.ButtonsConfig()
        var actions: [(() -> Void)] = []
        updateButtonEvent(model: model)
        // 产品定的没有生成签证文书就隐藏签字确认按钮
        let isSignFileOK = model.signFileOrigin.count > 0
        
        switch docType {
        case .powerOfAttorney, .settlementPlan, .explanatoryStatement:
            switch status {
            case .pendingConfirmation, .awaitingSignature:
                if let editEvent = editEvent {
                    actions.append(editEvent)
                }
                if let submitEvent = submitEvent {
                    actions.append(submitEvent)
                }
                
                if isSignFileOK {
                    config.names = ["在线编辑", "提交", "签字确认", "下载"]
                    config.style = .four
                    if let signatureConfirmationEvent = signatureConfirmationEvent {
                        actions.append(signatureConfirmationEvent)
                    }
                } else {
                    config.names = ["在线编辑", "提交", "下载"]
                    config.style = .three
                }
                if let downloadEvent = downloadEvent {
                    actions.append(downloadEvent)
                }
                config.actions = actions
            case .finalizing, .underReview, .completed:
                if let previewEvent = previewEvent {
                    actions.append(previewEvent)
                }
                if let downloadEvent = downloadEvent {
                    actions.append(downloadEvent)
                }
                config.names = ["查看", "下载"]
                config.actions = actions
                config.style = .two
            }
        case .qmasDoc:
            switch status {
            case .pendingConfirmation:
                if let infoConfirmationEvent = infoConfirmationEvent {
                    actions.append(infoConfirmationEvent)
                }
                if let downloadEvent = downloadEvent {
                    actions.append(downloadEvent)
                }
                config.names = ["信息确认", "下载"]
                config.actions = actions
                config.style = .two
            case .finalizing, .underReview, .completed:
                if let previewEvent = previewEvent {
                    actions.append(previewEvent)
                }
                if let downloadEvent = downloadEvent {
                    actions.append(downloadEvent)
                }
                config.names = ["查看", "下载"]
                config.actions = actions
                config.style = .two
            case .awaitingSignature:
                if let infoConfirmationEvent = infoConfirmationEvent {
                    actions.append(infoConfirmationEvent)
                }
                if isSignFileOK {
                    config.names = ["信息确认", "签字确认", "下载"]
                    config.style = .three
                    if let signatureConfirmationEvent = signatureConfirmationEvent {
                        actions.append(signatureConfirmationEvent)
                    }
                } else {
                    config.names = ["信息确认", "下载"]
                    config.style = .two
                }
                if let downloadEvent = downloadEvent {
                    actions.append(downloadEvent)
                }
                config.actions = actions
            }
        }
        return config
    }
}

extension YHResignDocumentDetailViewController {
    private func uploadFile(_ fileUrl: URL) {
        if let fileData = try? Data(contentsOf: fileUrl) {
            // 将文件数据上传到服务器
            let size = String(format: "%.2fM", Double(fileData.count) / (1024.0 * 1024.0))
            printLog("\(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 {
                    let uploadModel = YHResignDocumentUploadSignedDocument()
                    uploadModel.name = fileUrl.lastPathComponent
                    uploadModel.url = successUrl
                    self.viewModel.uploadSignedDoc(self.docId, type: .upload, [uploadModel]) { [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.requestData(isNeedLoading: true)
                    }
                    return
                }
                var msg = "上传文件失败"
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    msg = errorMsg
                }
                YHHUD.flash(message: msg)
            }
        } else {
            YHHUD.flash(message: "识别文件失败")
        }
    }
    
    private func uploadImages(imgArr: [YHSelectImageItem]) {
        let group = DispatchGroup()
        var successArr: [YHResignDocumentUploadSignedDocument] = []
        var failArr: [YHSelectImageItem] = []
        
        YHHUD.show(.progress(message: "上传中..."))
        for item in imgArr {
            if let image = item.data {
                group.enter()
                self.uploadImage(image, imageName: item.name) { success, url in
                    if success {
                        let doc = YHResignDocumentUploadSignedDocument()
                        doc.name = item.name
                        doc.url = url
                        successArr.append(doc)
                    } else {
                        failArr.append(item)
                    }
                    group.leave()
                }
            }
        }
        
        // 等待所有任务完成
        group.notify(queue: .main) {
            // 所有任务完成，回到主线程继续执行
            YHHUD.hide()
            printLog("所有任务完成")
            if imgArr.count == successArr.count {
                YHHUD.flash(message: "上传成功")
            } else {
                YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
            }
            
            self.viewModel.uploadSignedDoc(self.docId, type: .upload, successArr) { [weak self] success, error in
                guard let self = self else { return }
                self.requestData(isNeedLoading: true)
            }
        }
    }
    
    private func uploadImage(_ img: UIImage, imageName: String, callBack: @escaping (Bool, String) -> Void) {
        // 先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 submitAllUploadFiles() {
        guard let detailModel = detailModel, detailModel.signedDocument.count > 0 else {
            return
        }
        let docs = detailModel.signedDocument.map { model in
            let uploadModel = YHResignDocumentUploadSignedDocument()
            uploadModel.name = model.fileName
            uploadModel.url = model.url
            return uploadModel
        }
        
        self.viewModel.uploadSignedDoc(self.docId, type: .upload, docs) { [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.requestData(isNeedLoading: true)
        }
    }
}

private extension YHCertificateEditType {
    func editName() -> String {
        switch self {
        case .rename:
            return "重命名"
        case .preview:
            return "预览"
        case .delete:
            return "删除"
        case .cancel:
            return "取消"
        case .reupload:
            return "重传"
        case .sendEmail:
            return "发送到邮箱"
        }
    }
}

private extension YHResignDocumentType {
    
    func attributedTips() -> ASAttributedString {
        let dotStr: ASAttributedString = "\(.image(UIImage(named: "tip_list_index_dot") ?? UIImage(), .custom(.center, size: .init(width: 3, height: 3))))"
        let spaceStr: ASAttributedString = "\(.image(UIImage(), .custom(.center, size: .init(width: 8, height: 3))))"
        let indentStr = dotStr + spaceStr
        let downloadStr: ASAttributedString = .init(string: "您也可以下载文件后完成信息确认，并上传已签署件", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
        switch self {
        case .powerOfAttorney:
            let firstLine: ASAttributedString = .init(string: "请您尽快核对信息，如信息有误，可进行在线编辑\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let secondLineL: ASAttributedString = .init(string: "如信息无误，请主申请人在", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let secondLineR: ASAttributedString = .init(string: "右下角的位置完成电子签字\n", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            let secondLine = (secondLineL + secondLineR)
            return (indentStr + firstLine + indentStr + secondLine + indentStr + downloadStr).add(attributes: .paragraph(.lineSpacing(8), .firstLineHeadIndent(0), .headIndent(11)))
        case .qmasDoc:
            let firstLine: ASAttributedString = .init(string: "需填写完整邮箱、电话号码（内地电话号码或香港电话号码）、日期（填写当下日期即可）\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            
            let secondLine: ASAttributedString = .init(string: "请主申请人勾选信息并完成电子签字\n", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            return (indentStr + firstLine + indentStr + secondLine + indentStr + downloadStr).add(attributes: .paragraph(.lineSpacing(8), .firstLineHeadIndent(0), .headIndent(11)))
        case .settlementPlan:
            let firstLine: ASAttributedString = .init(string: "如需调整和补充内容，请在文档中进行编辑\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let secondLine: ASAttributedString = .init(string: "编辑完成后，点击“完成编辑，提交”\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let third: ASAttributedString = .init(string: "我们将根据您的修改调整文书\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let fourth1: ASAttributedString = .init(string: "如您对《定居计划书》无其他补充建议，", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let fourth2: ASAttributedString = .init(string: "请您在文书尾部进行电子签字\n", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            return (indentStr + firstLine + indentStr + secondLine + indentStr + third + indentStr + fourth1 + fourth2 + indentStr + downloadStr).add(attributes: .paragraph(.lineSpacing(8), .firstLineHeadIndent(0), .headIndent(11)))
        case .explanatoryStatement:
            let firstLine: ASAttributedString = .init(string: "如需调整和补充内容，请在文档中进行编辑\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let secondLine: ASAttributedString = .init(string: "编辑完成后，点击“完成编辑，提交”\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let third: ASAttributedString = .init(string: "我们将根据您的修改调整文书\n", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let fourth1: ASAttributedString = .init(string: "如您对《解释说明书》无其他补充建议，", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let fourth2: ASAttributedString = .init(string: "请您在文书尾部进行电子签字\n", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            return (indentStr + firstLine + indentStr + secondLine + indentStr + third + indentStr + fourth1 + fourth2 + indentStr + downloadStr).add(attributes: .paragraph(.lineSpacing(8), .firstLineHeadIndent(0), .headIndent(11)))
        }
    }
}
