//
//  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, _ details: [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)
    }
    
    enum ActionType {
        case upload
        case reupload
        case delete
    }
    
    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
    // 进签字、QMAS信息确认等再出来就要刷新接口，而上传文件预览文件就不能刷新接口，
    // 因此增加这个字段判断，后续如果有跳其他页面且退回该页面需要刷新状态设置为true
    private var isNeedUpdateData: Bool = true
        
    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(YHResignDocumentMultiLineTipsCell.self, forCellReuseIdentifier: YHResignDocumentMultiLineTipsCell.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()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let needLoading = isNeedShowLoading
        isNeedShowLoading = false
        if isNeedUpdateData {
            isNeedUpdateData = 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
            guard let self = self else {
                return
            }
            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)
                }
                self.datas = []
                self.tableView.reloadData()
                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)]
                self.datas.removeAll()
                self.datas.append(firstSetcion)
                self.datas.append(secondSetcion)
                let uploadSection = getUploadSection(status: status, model: documentModel)
                if uploadSection.count > 0 {
                    self.datas.append(uploadSection)
                }
                self.tableView.reloadData()
            } else {
                self.datas = []
                self.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.isEnabled = 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)
    }
    
    private func previewUploadedFiles(_ urlStr: String, title: String) {
        guard URL(string: urlStr) != nil else {
            return
        }
        YHHUD.show(.progress(message: ""))
        viewModel.getRealUsefulUrl(urlStr) { [weak self] resultUrl in
            guard let self = self else { return }
            YHHUD.hide()
            self.previewFileTool.openXLSXRemoteFile(urlString: resultUrl, fileName: title)
        }
    }
}

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, details):
            if let cell = tableView.dequeueReusableCell(withIdentifier: YHResignDocumentMultiLineTipsCell.cellReuseIdentifier) as? YHResignDocumentMultiLineTipsCell {
                cell.setupCellInfo(title: title, details: details)
                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 {
                            let sheetView = YHDocumentUploadView.sheetView()
                            sheetView.maxSelectCount = 1
                            sheetView.uploadFilesBlock = { [weak self] fileUrl in
                                guard let self = self else { return }
                                printLog(fileUrl)
                                self.uploadFile(fileUrl, actionType: .reupload, oldUrl: urlStr)
                            }
                            sheetView.uploadImageBlock = { [weak self] imgArr in
                                guard let self = self else { return }
                                self.uploadImages(imgArr: imgArr, actionType: .reupload, oldUrl: urlStr)
                            }
                            sheetView.show()
                        } else if editType == .delete { // 删除
                            // 增加二次弹窗确认
                            let message0: ASAttributedString = .init(string: "您确定要删除文档", .font(UIFont.PFSC_R(ofSize: 16)), .foreground(UIColor.mainTextColor))
                            let message1: ASAttributedString = .init(string: "\(title)", .font(UIFont.PFSC_M(ofSize: 16)), .foreground(UIColor.brandMainColor))
                            let message2: ASAttributedString = .init(string: "吗？", .font(UIFont.PFSC_R(ofSize: 16)), .foreground(UIColor.mainTextColor))
                            YHCommonAlertView.show(title: nil, attributedMessage: message0 + message1 + message2, "取消", "确认", fullGuestureEnable: false) {
                            } callBack: { [weak self] in
                                guard let self = self else {
                                    return
                                }
                                if let index = self.detailModel?.signedDocument.firstIndex(where: { model in
                                    model.url == urlStr
                                }) {
                                    self.detailModel?.signedDocument.remove(at: index)
                                    self.updateUploadFilesSection()
                                }
                            }
                            
                        } else if editType == .preview { // 预览
                            self.previewUploadedFiles(urlStr, title: title)
                        }
                    }.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, actionType: .upload, oldUrl: nil)
                    }
                    sheetView.uploadImageBlock = { [weak self] imgArr in
                        guard let self = self else { return }
                        self.uploadImages(imgArr: imgArr, actionType: .upload, oldUrl: nil)
                    }
                    sheetView.show()
                }
                cell.sureButtonClickEvent = { [weak self] in
                    guard let self = self else { return }
                    // 产品说增加二次弹窗确认
                    YHCommonAlertView.show("", "确认提交？", "取消", "确认", fullGuestureEnable: false) {
                    } callBack: { [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()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        guard datas.count > indexPath.section else {
            return
        }
        let sectionArr = datas[indexPath.section]
        guard sectionArr.count > indexPath.row else {
            return
        }
        let item = sectionArr[indexPath.row]
        if case let .uploadFile(title, urlStr, _) = item {
            previewUploadedFiles(urlStr, title: title)
        }
    }
}

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 {
                    var errorMsg = "文书正在生成中，请稍后再试"
                    if let error = error, error.errorMsg.count > 0 {
                        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 {
                        var errorMsg = "提交失败"
                        if let error = error, error.errorMsg.count > 0 {
                            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)")
                        var errorMsg = "签字文书正在生成中，请稍后再试"
                        if error.errorMsg.count > 0 {
                            errorMsg = error.errorMsg
                        }
                        YHHUD.flash(message: errorMsg)
                    }
                    return
                }
                self.isNeedShowLoading = true
                self.isNeedUpdateData = 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, urlString.count > 0 {
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.getPublicImageUrl(urlString) { [weak self] success, error in
                        YHHUD.hide()
                        guard let self = self else {
                            return
                        }
                        if let success = success, let url = URL(string: success) {
                            self.previewFile(url)
                        } else {
                            var errorMsg = "文书正在生成中，请稍后再试"
                            if let error = error, error.errorMsg.count > 0 {
                                errorMsg = error.errorMsg
                            }
                            YHHUD.flash(message: errorMsg)
                        }
                    }
                } else {
                    var errorMsg = "文书正在生成中，请稍后再试"
                    if let error = error, error.errorMsg.count > 0 {
                        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 {
                self.isNeedUpdateData = true
                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: .sendToWechat, title: "分享至微信"),
                         YHCertificateEditItem(type: .sendEmail, title: "发送至邮箱"),
                         YHCertificateEditItem(type: .cancel, title: "取消")]
            YHCertificateEditSheetView.sheetView(items: items, sheetTitle: "请选择下载方式") {
                [weak self] editType in
                guard let self = self else { return }
                if editType == .sendEmail {
                    IQKeyboardManager.shared.isEnabled = false
                    self.emailInputView.textField.text = ""
                    self.emailInputView.textField.becomeFirstResponder()
                } else if editType == .sendToWechat {
                    YHHUD.show(.progress(message: "加载中..."))
                    self.viewModel.getOriginalDoc(docId: model.docId) { [weak self] model, error in
                        YHHUD.hide()
                        guard let self = self else {
                            return
                        }
                        // 可能是私域链接也可能是公域，用统一方法处理
                        if let urlString = model?.url, urlString.count > 0 {
                            YHHUD.show(.progress(message: "加载中..."))
                            self.viewModel.getRealUsefulUrl(urlString) { [weak self] success in
                                YHHUD.hide()
                                guard let self = self else {
                                    return
                                }
                                if success.count > 0, let url = URL(string: success) {
                                    self.downloadRemoteFile(url: url) { [weak self] destination in
                                        guard let self = self else {
                                            return
                                        }
                                        if let destination = destination, !destination.absoluteString.isEmpty {
                                            DispatchQueue.main.async {
                                                YHShareManager.shared.shareFileToWeChat(fileUrl: destination, filename: self.name + "." + destination.pathExtension.lowercased(), ext: destination.pathExtension.lowercased())
                                            }
                                        }
                                    }
                                } else {
                                    var errorMsg = "文书正在生成中，请稍后再试"
                                    if let error = error, error.errorMsg.count > 0 {
                                        errorMsg = error.errorMsg
                                    }
                                    YHHUD.flash(message: errorMsg)
                                }
                            }
                        } else {
                            var errorMsg = "文书正在生成中，请稍后再试"
                            if let error = error, error.errorMsg.count > 0 {
                                errorMsg = error.errorMsg
                            }
                            YHHUD.flash(message: errorMsg)
                        }
                    }
                }
            }.show()
        }
    }
    
    private func downloadRemoteFile(url: URL, completiton: @escaping (_ destination: URL?) -> Void) {
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        DispatchQueue.main.async {
            YHHUD.show(.progress(message: "加载文件中..."))
        }
        let task = session.downloadTask(with: url) { (tempLocalUrl, response, error) in
            DispatchQueue.main.async {
                YHHUD.hide()
            }
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // 下载完成，尝试打开文件
                let fileManager = FileManager.default
                let destination = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(response?.suggestedFilename ?? UUID().uuidString)
                do {
                    if fileManager.fileExists(atPath: destination.path) {
                        try fileManager.removeItem(at: destination)
                    }
                    try fileManager.moveItem(at: tempLocalUrl, to: destination)
                    completiton(destination)
                } catch {
                    completiton(nil)
                    DispatchQueue.main.async {
                        YHHUD.flash(message: "下载文件失败")
                    }
                }
            } else {
                completiton(nil)
                DispatchQueue.main.async {
                    YHHUD.flash(message: "下载文件失败")
                }
            }
        }
        task.resume()
    }
    
    private func getFileExtenion(_ fileUrl: String) -> String {
        var extenion = ""
        if let url = URL(string: fileUrl) {
            extenion = "." + url.pathExtension
        }
        return extenion
    }
    
    private func getUploadSection(status: YHResignDocumentStatus, model: YHResignDocumentCompleteModel) -> [RowType] {
        var uploadSection: [RowType] = []
        if status == .pendingConfirmation || status == .awaitingSignature {
            uploadSection.append(.uploadHeader("上传已签署件"))
            model.signedDocument.enumerated().forEach { [weak self] index, file in
                guard let self = self else {
                    return
                }
                let extenionName = self.getFileExtenion(file.url)
                uploadSection.append(.uploadFile(self.name + "\(index + 1)" + extenionName, file.url, [.preview, .reupload, .delete, .cancel]))
            }
            var name = "上传已签署件"
            var isUploadEnable = true
            let isSureButtonEnable = model.signedDocument.count > 0
            if model.signedDocument.count == uploadMaxCount {
                name = "继续上传"
                isUploadEnable = true
            } 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.enumerated().forEach { [weak self] index, file in
                    guard let self = self else {
                        return
                    }
                    let extenionName = self.getFileExtenion(file.url)
                    uploadSection.append(.uploadFile(self.name + "\(index + 1)" + extenionName, file.url, [.preview, .cancel]))
                }
            }
        }
        return uploadSection
    }
    
    private func updateUploadFilesSection() {
        guard let model = detailModel else {
            return
        }
        var uploadSection: [RowType] = []
        uploadSection.append(.uploadHeader("上传已签署件"))
        model.signedDocument.enumerated().forEach { [weak self] index, file in
            guard let self = self else { return }
            let extenionName = self.getFileExtenion(file.url)
            uploadSection.append(.uploadFile(self.name + "\(index + 1)" + extenionName, file.url, [.preview, .reupload, .delete, .cancel]))
        }
        
        var name = "上传已签署件"
        var isUploadEnable = true
        let totalCount = model.signedDocument.count
        let isSureButtonEnable = totalCount > 0
        if totalCount >= uploadMaxCount {
            name = "继续上传"
            isUploadEnable = true
        } else if totalCount > 0 {
            name = "继续上传"
            isUploadEnable = true
        }
        uploadSection.append(.uploadAction(name, isUploadEnable, isSureButtonEnable, isSureButtonEnable ? 4 : 16))
        if let index = datas.firstIndex(where: { sectionArr in
            return sectionArr.contains { rowType in
                if case.uploadHeader = rowType {
                    return true
                }
                return false
            }
        }) {
            datas[index] = uploadSection
        }
        tableView.reloadData()
    }
    
    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, actionType: ActionType, oldUrl: String?) {
        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 = YHResignSignedDocumentModel()
                    uploadModel.url = successUrl
                    let extenionName = self.getFileExtenion(successUrl)
                    uploadModel.fileName = self.name + "\((self.detailModel?.signedDocument.count ?? 0) + 1)" + extenionName
                    if actionType == .upload {
                        self.detailModel?.signedDocument.append(uploadModel)
                    } else if actionType == .reupload {
                        if let index = self.detailModel?.signedDocument.firstIndex(where: {
                            $0.url == oldUrl && oldUrl != nil
                        }) {
                            self.detailModel?.signedDocument[index] = uploadModel
                        }
                    }
                   
                    self.updateUploadFilesSection()
                    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], actionType: ActionType, oldUrl: String?) {
        let group = DispatchGroup()
        var successArr: [YHResignSignedDocumentModel] = []
        var failArr: [YHSelectImageItem] = []
        
        YHHUD.show(.progress(message: "上传中..."))
        for item in imgArr {
            if let image = item.data {
                group.enter()
                self.uploadImage(image) { success, url in
                    if success {
                        let doc = YHResignSignedDocumentModel()
                        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)张照片上传失败")
            }
            if actionType == .upload {
                let count = self.detailModel?.signedDocument.count ?? 0
                successArr.enumerated().forEach { [weak self] index, file in
                    guard let self = self else { return }
                    let extenionName = self.getFileExtenion(file.url)
                    file.fileName = self.name + "\(count + 1 + index)" + extenionName
                }
                self.detailModel?.signedDocument.append(contentsOf: successArr)
            } else if actionType == .reupload {
                if let index = self.detailModel?.signedDocument.firstIndex(where: {
                    $0.url == oldUrl && oldUrl != nil
                }) {
                    if let newUrl = successArr.first?.url {
                        let extenionName = self.getFileExtenion(newUrl)
                        self.detailModel?.signedDocument[index].url = newUrl
                        self.detailModel?.signedDocument[index].fileName = self.name + "\(index)" + extenionName
                    }
                }
            }
            self.updateUploadFilesSection()
        }
    }
    
    private func uploadImage(_ img: UIImage, callBack: @escaping (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, "")
        }
    }
    
    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: .submit, 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 "发送到邮箱"
        case .sendToWechat:
            return "分享至微信"
        }
    }
}

private extension YHResignDocumentType {
    
    func attributedTips() -> [ASAttributedString] {
        let downloadStr: ASAttributedString = .init(string: "您也可以下载文件后完成信息确认，并上传已签署件", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
        // .add(attributes: .paragraph(.lineSpacing(4), .firstLineHeadIndent(0), .headIndent(11)))
        switch self {
        case .powerOfAttorney:
            let firstLine: ASAttributedString = .init(string: "请您尽快核对信息，如信息有误，可进行在线编辑", .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: "右下角的位置完成电子签字", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            let secondLine = (secondLineL + secondLineR)
            return [firstLine, secondLine, downloadStr]
        case .qmasDoc:
            let firstLine: ASAttributedString = .init(string: "需填写完整邮箱、电话号码（内地电话号码或香港电话号码）、日期（填写当下日期即可）", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            
            let secondLine: ASAttributedString = .init(string: "请主申请人勾选信息并完成电子签字", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            return [firstLine, secondLine, downloadStr]
        case .settlementPlan:
            let firstLine: ASAttributedString = .init(string: "如需调整和补充内容，请在文档中进行编辑", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let secondLine: ASAttributedString = .init(string: "编辑完成后，点击“完成编辑，提交”", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let third: ASAttributedString = .init(string: "我们将根据您的修改调整文书", .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: "请您在文书尾部进行电子签字", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            return [firstLine, secondLine, third, fourth1 + fourth2, downloadStr]
        case .explanatoryStatement:
            let firstLine: ASAttributedString = .init(string: "如需调整和补充内容，请在文档中进行编辑", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let secondLine: ASAttributedString = .init(string: "编辑完成后，点击“完成编辑，提交”", .font(UIFont.PFSC_R(ofSize: 12)), .foreground(UIColor.mainTextColor70))
            let third: ASAttributedString = .init(string: "我们将根据您的修改调整文书", .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: "请您在文书尾部进行电子签字", .font(UIFont.PFSC_B(ofSize: 12)), .foreground(UIColor.brandMainColor))
            return [firstLine, secondLine, third, fourth1 + fourth2, downloadStr]
        }
    }
}
