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

import UIKit
import IQKeyboardManagerSwift
import AttributedString

class YHResignUploadDocDetailViewController: YHBaseViewController {
    
    // 进入该页面以下三个参数必传
    // 订单id
    var id: Int = 0
    
    var materialModel: YHResignUploadDetailModel = YHResignUploadDetailModel()
    var templateArr: [YHResignUploadDetailTemplateListModel] = []
    var viewModel: YHResignUploadDetailViewModel = YHResignUploadDetailViewModel()
    var items: [YHResignUploadDetailFileListModel] = []
    var selectEditItem: YHResignUploadDetailFileListModel?
    var clickInputViewIndex: Int = 0
    lazy var previewFileTool: YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()

    var renameInputView: YHFileRenameInputView = {
        let view = YHFileRenameInputView.inputView(defalutText: "请输入名称")
        return view
    }()

    var reasonInputView: YHFileExplainReasonInputView = {
        let view = YHFileExplainReasonInputView.inputView(defalutText: "请输入名称")
        return view
    }()
    
    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 tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 0.01
        tableView.estimatedSectionFooterHeight = 0.01
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .white
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateTemplateCell.self, forCellReuseIdentifier: YHCertificateTemplateCell.cellReuseIdentifier)
        tableView.register(YHResignUploadDetailFileNameCell.self, forCellReuseIdentifier: YHResignUploadDetailFileNameCell.cellReuseIdentifier)
        tableView.register(cellWithClass: YHAdopterUploadTableViewCell.self)
        tableView.register(cellWithClass: YHAdopterIncomeFileCountTableViewCell.self)
        
        return tableView
    }()
    
    lazy var uploadBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("确认".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickUploadBtn), for: .touchUpInside)
        return btn
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .white
        self.gk_navTitle = "资料上传"
        
        addKeyBoardNotify()
        createUI()
        requestMaterialDetail()
        
        renameInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            if let selectEditItem = selectEditItem, var text = text {
                // 重命名
                text = text + "." + selectEditItem.getFileSuffixName()
                selectEditItem.name = text
                tableView.reloadData()
            }
        }
        
        reasonInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            if var text = text {
                // 重命名
                self.materialModel.unavailable_reason = text
                tableView.reloadData()
            }
        }
    }
    
    deinit {
        removeNotify()
    }
    
    @objc func didClickUploadBtn() {
        if self.materialModel.unavailable_reason.count != 0 {
            YHHUD.show(.progress(message: ""))
            self.viewModel.postUploadDocFillUnavailableReason(id: id, reason: self.materialModel.unavailable_reason) {[weak self] success, _ in
                YHHUD.hide()
                guard let self = self else { return }
                if success {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        } else {
            if self.items.count == 0 {
                YHHUD.flash(message: "请上传必填文件")
                return
            }
            YHHUD.show(.progress(message: ""))
            self.viewModel.postUploadDocUpload(id: id, file: self.items) { [weak self] success, _ in
                YHHUD.hide()
                guard let self = self else { return }
                if success {
                    self.navigationController?.popViewController(animated: true)
                }
            }
        }
    }
    
    func createUI() {

        view.addSubview(uploadBtn)
        view.addSubview(tableView)
        view.addSubview(blackMaskView)
        view.addSubview(renameInputView)
        view.addSubview(reasonInputView)

        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(-98)
        }
        uploadBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(48.0)
            make.bottom.equalToSuperview().offset(-8-k_Height_safeAreaInsetsBottom())
        }
        renameInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHFileRenameInputView.height)
            make.bottom.equalToSuperview().offset(YHFileRenameInputView.height)
        }
        reasonInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHFileExplainReasonInputView.height)
            make.bottom.equalToSuperview().offset(YHFileExplainReasonInputView.height)
        }
    }
    
    func uploadImage(_ img: UIImage, imageName: String, callBack: ((Bool, String) -> Void)?) {
        // 先OSS上传得到URL
        self.viewModel.uploadImage(img) {
            [weak self] url, _ in
            guard self != nil else { return }
            if let url = url, !url.isEmpty {
                callBack?(true, url)
                return
            }
            callBack?(false, "")
        }
    }
    
    func uploadFile(_ fileUrl: URL) {
        if let fileData = try? Data(contentsOf: fileUrl) {
            // 将文件数据上传到服务器
            let size = String(format: "%.2fM", Double(fileData.count)/(1024.0 * 1024.0))
//            print("\(size)")
            // 先OSS上传得到URL
            YHHUD.show(.progress(message: "上传中..."))
            self.viewModel.uploadFile(fileUrl.absoluteString) {
                [weak self] successUrl, error in
                
                YHHUD.hide()
                
                guard let self = self else { return }
                
                // 再调用业务接口
                if let successUrl = successUrl, !successUrl.isEmpty {
                    var fileName = fileUrl.lastPathComponent
                    if fileName.isEmpty {
                        fileName = successUrl.lastPathComponent
                    }
                    let suffixName = successUrl.pathExtension.lowercased()
                    let timestamp = Date().timeIntervalSince1970
                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "yyyy.MM.dd HH:mm:ss"
                    let currentDate = Date()
                    let formattedDate = dateFormatter.string(from: currentDate)
                    let model = YHResignUploadDetailFileListModel()
                    model.url = successUrl
                    model.name = fileName
                    model.updated_at = formattedDate
                    self.items.append(model)
                    self.tableView.reloadData()
                    YHHUD.flash(message: "上传成功")
                    return
                }
                var msg = "上传文件失败"
                if let errorMsg = error?.errorMsg, !errorMsg.isEmpty {
                    msg = errorMsg
                }
                YHHUD.flash(message: msg)
            }
        } else {
            YHHUD.flash(message: "识别文件失败")
        }
    }
}

extension YHResignUploadDocDetailViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.materialModel.status == 0 || self.materialModel.status == 1 {
            return 2
        }
        return 4
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return templateArr.count
        }
        if section == 1 {
            return items.count
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateTemplateCell.cellReuseIdentifier, for: indexPath) as? YHCertificateTemplateCell else { return UITableViewCell() }
            cell.update(bottomMargin: 15)
            if 0 <= indexPath.row && indexPath.row < templateArr.count {
                cell.resignUploadDetailTemplateListModel = templateArr[indexPath.row]
            }
            return cell
        }
        if indexPath.section == 1 {
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHResignUploadDetailFileNameCell.cellReuseIdentifier, for: indexPath) as? YHResignUploadDetailFileNameCell else {
                return UITableViewCell()
            }
            if 0 <= indexPath.row && indexPath.row < items.count {
                let item = items[indexPath.row]
                cell.updateModel(item)
                cell.editBlock = {
                    
                    [weak self] contentItem in
                    guard let self = self else { return }
                    selectEditItem = contentItem
                    var items = [YHCertificateEditItem(type: .rename, title: "重命名"),
                                 YHCertificateEditItem(type: .preview, title: "预览"),
                                 YHCertificateEditItem(type: .delete, title: "删除"),
                                 YHCertificateEditItem(type: .cancel, title: "取消")]
                    
                    if self.materialModel.status == 0 || self.materialModel.status == 1 {
                        
                        items = [YHCertificateEditItem(type: .preview, title: "预览"),
                                 YHCertificateEditItem(type: .cancel, title: "取消")]
                    }
                    
                    YHCertificateEditSheetView.sheetView(items: items) {
                        [weak self] editType in
                        guard let self = self else { return }
                        print("editType:\(editType.rawValue)")
                        
                        if editType == .rename { // 重命名
                            IQKeyboardManager.shared.isEnabled = false
                            clickInputViewIndex = 0
                            var name = contentItem.getFileNameWithoutSuffix()
                            if name.count > 30 {
                                name = name[safe: ..<30]!
                            }
                            renameInputView.textField.text = name
                            renameInputView.textField.becomeFirstResponder()
                            
                        } else if editType == .delete { // 删除
                            let msg = "您确定要删除文档\(contentItem.name)吗?"
                            YHTwoOptionAlertView.showAlertView(message: msg) { sure in
                                if !sure { return }
                                // 删除
                                var deleteIndex = -1
                                for (index, item) in self.items.enumerated() {
                                    if contentItem.url == item.url {
                                        deleteIndex = index
                                        break
                                    }
                                }
                                self.items.remove(at: deleteIndex)
                                self.tableView.reloadData()
                            }
                            
                        } else if editType == .preview { // 预览
                            print(contentItem.url)
                            self.viewModel.getPublicImageUrl(contentItem.url) { success, _ in
                                if let success = success {
                                    self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: contentItem.name)
                                }
                            }
                        }
                    }.show()
                }
            }
            return cell
        }
        if indexPath.section == 2 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterUploadTableViewCell.self)
            cell.newFileBlock = {[weak self] in
                guard let self = self else { return }
                let count = self.items.count
                if count >= 10 {
                    YHHUD.flash(message: "最多上传10个图片或文件")
                    return
                }
                var maxCount = 10 - count
                if maxCount > 9 {
                    maxCount = 9
                }
                let sheetView = YHCertificateUploadSheetView.sheetView()
                sheetView.tips = "支持的文件格式为jpg/jpeg、png、pdf，最多可上传10张图片或文件"
                sheetView.maxSelectImageCount = maxCount
                sheetView.fileTypes = [ "public.image",
                                        "com.adobe.pdf"]
                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()
                        // 所有任务完成，回到主线程继续执行
                        if imgArr.count == successArr.count {
                            YHHUD.flash(message: "上传成功")
                            for item in successArr {
                                let timestamp = Date().timeIntervalSince1970
                                let dateFormatter = DateFormatter()
                                dateFormatter.dateFormat = "yyyy.MM.dd HH:mm:ss"
                                let currentDate = Date()
                                let formattedDate = dateFormatter.string(from: currentDate)
                                let model = YHResignUploadDetailFileListModel()
                                model.url = item
                                model.name = "\(UInt64(timestamp))" + ".jpg"
                                model.updated_at = formattedDate
                                self.items.append(model)
                            }
                            self.tableView.reloadData()
                        } else {
                            YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
                        }
                        
                    }
                }
                sheetView.show()
            }
            return cell
        }
        if indexPath.section == 3 {
            let cell = tableView.dequeueReusableCell(withClass: YHAdopterIncomeFileCountTableViewCell.self)
            cell.setContentData(self.items.count)
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return 77.0
        }
        if indexPath.section == 2 {
            return 57
        }
        if indexPath.section == 3 {
            return 41
        }
        return 55.0
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 56
        }
        if section == 1 {
            return UITableView.automaticDimension
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0 { // 证件示例模板
            let titlelabel = UILabel()
            titlelabel.textColor = UIColor.mainTextColor
            titlelabel.textAlignment = .left
            titlelabel.font = UIFont.PFSC_M(ofSize: 17)
            titlelabel.text = "示例模板"
            titlelabel.numberOfLines = 0
            view.addSubview(titlelabel)
            
            titlelabel.snp.makeConstraints { make in
                make.top.equalToSuperview().offset(16)
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
            }
            
            let tipsLabel = UILabel()
            tipsLabel.textColor = UIColor.labelTextColor2
            tipsLabel.textAlignment = .left
            tipsLabel.font = UIFont.PFSC_R(ofSize: 14)
            tipsLabel.numberOfLines = 0
//            if !self.templateModel.remark.isEmpty {
//                tipsLabel.text = "注意事项：\(self.templateModel.remark)"
//            }
            view.addSubview(tipsLabel)
            
            tipsLabel.snp.makeConstraints { make in
                make.top.equalTo(titlelabel.snp.bottom).offset(5)
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.bottom.equalToSuperview().offset(-15)
            }
            return view
        }
        if section == 1 {
            if self.materialModel.status == 2 {
                let rejectView = UIView()
                view.addSubview(rejectView)
                let warningImgV = UIImageView(image: UIImage(named: "my_cer_upload_warning"))
                rejectView.addSubview(warningImgV)
                let rejectTitleLabel = UILabel()
                rejectTitleLabel.textColor = .failColor
                rejectTitleLabel.font = UIFont.PFSC_R(ofSize: 12)
                rejectTitleLabel.textAlignment = .left
                rejectTitleLabel.numberOfLines = 0
                rejectTitleLabel.text = "驳回原因：" + self.materialModel.reject_reason
                
                rejectView.addSubview(rejectTitleLabel)
                rejectView.snp.makeConstraints { make in
                    make.left.equalToSuperview().offset(20)
                    make.right.equalToSuperview().offset(-20)
                    make.bottom.equalToSuperview().offset(-12)
                    make.top.equalToSuperview().offset(12)
                }
                warningImgV.snp.makeConstraints { make in
                    make.width.height.equalTo(14)
                    make.left.top.equalTo(0)
                }
                rejectTitleLabel.snp.makeConstraints { make in
                    make.top.right.bottom.equalToSuperview()
                    make.left.equalTo(warningImgV.snp.right).offset(4)
                }
            }
        }
        
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01)
        return view
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
        if section == 0 {
            return UITableView.automaticDimension
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        if section == 0 {
            // 证件标题和状态
            let titlelabel = UITextView()
            titlelabel.textColor = UIColor.mainTextColor
            titlelabel.font = UIFont.PFSC_M(ofSize: 16)
            titlelabel.isScrollEnabled = false
            titlelabel.isEditable = false
            titlelabel.isSelectable = false
            view.addSubview(titlelabel)
            
            let statusLabel = UILabel()
            statusLabel.textAlignment = .center
            statusLabel.font = UIFont.PFSC_M(ofSize: 10)
            statusLabel.layer.cornerRadius = 2
            statusLabel.clipsToBounds = true
            statusLabel.frame = CGRect(x: 0, y: 0, width: 38, height: 16)
            view.addSubview(statusLabel)
            
            var text = ""
            var textColor: UIColor = UIColor(hexString: "#0046B5")!
            var bgColor: UIColor = UIColor(hexString: "#F0F4FB", transparency: 0.08)!
            
            if self.materialModel.status == 0 {
                text = "审核中".local
                textColor = UIColor(hexString: "#FF9900")!
                bgColor = UIColor(hexString: "#FF9900", transparency: 0.08)!
                
            } else if self.materialModel.status == 3 {
                
                text = "待上传".local
                textColor = UIColor(hexString: "#0046B5")!
                bgColor = UIColor(hexString: "#F0F4FB")!
                
            } else if self.materialModel.status == 1 {
                text =  "已完成".local
                textColor = UIColor(hexString: "#49D2B1")!
                bgColor = UIColor(hexString: "#49D2B1", transparency: 0.08)!
                
            } else if self.materialModel.status == 2 {
                text =  "已驳回".local
                textColor = UIColor.failColor
                bgColor = UIColor(hexString: "#F81D22", transparency: 0.08)!
            }
            statusLabel.text = text
            statusLabel.textColor = textColor
            statusLabel.backgroundColor = bgColor
            let tipsLabel = UILabel()
            tipsLabel.textColor = .labelTextColor2
            tipsLabel.font = UIFont.PFSC_R(ofSize: 14)
            tipsLabel.textAlignment = .left
            tipsLabel.numberOfLines = 0
            
            tipsLabel.text = self.materialModel.description
            view.addSubview(tipsLabel)
            
            let noLabel = UILabel()
            let c = ASAttributedString.init("如无法提供，请点击这里", .font(UIFont.PFSC_M(ofSize: 14)), .foreground(UIColor.labelTextColor2), .underline(.single), .action {
                // 说明原
                if self.materialModel.status == 0 || self.materialModel.status == 1 {
                    
                } else {
                    self.clickInputViewIndex = 1
                    IQKeyboardManager.shared.isEnabled = false
                    self.reasonInputView.textField.text = self.materialModel.unavailable_reason
                    self.reasonInputView.textField.becomeFirstResponder()
                }
                
            })
            noLabel.attributed.text = c
            
            var cerName: ASAttributedString = .init(string: self.materialModel.name, .font(UIFont.PFSC_M(ofSize: 17)), .foreground(UIColor.mainTextColor))
            let template: ASAttributedString = " \(.view(statusLabel, .original(.center)))"
            cerName += template
            titlelabel.attributed.text = cerName

            view.addSubview(noLabel)
            
            titlelabel.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(15)
                make.right.equalToSuperview().offset(-20)
                make.top.equalTo(17)
            }
            
            tipsLabel.snp.remakeConstraints { make in
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.top.equalTo(titlelabel.snp.bottom).offset(8)
                make.bottom.equalTo(-32)
            }
            
            noLabel.snp.remakeConstraints { make in
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.height.equalTo(20)
                make.top.equalTo(tipsLabel.snp.bottom).offset(12)
            }
            
            if self.materialModel.status == 0 || self.materialModel.status == 1 {
                noLabel.isHidden = true
                tipsLabel.snp.remakeConstraints { make in
                    make.left.equalToSuperview().offset(20)
                    make.right.equalToSuperview().offset(-20)
                    make.top.equalTo(titlelabel.snp.bottom).offset(8)
                    make.bottom.equalTo(-12)
                }
            }
            
            if self.materialModel.unavailable_reason.count != 0 {

                let bgView = UIView()
                bgView.backgroundColor = UIColor.contentBkgColor
                view.addSubview(bgView)
                
                let unavailableLabel = UILabel()
                unavailableLabel.textColor = .mainTextColor50
                unavailableLabel.font = UIFont.PFSC_R(ofSize: 14)
                unavailableLabel.textAlignment = .left
                unavailableLabel.numberOfLines = 0
                
                unavailableLabel.text = "原因：" + self.materialModel.unavailable_reason
                
                bgView.addSubview(unavailableLabel)
                tipsLabel.snp.remakeConstraints { make in
                    make.left.equalToSuperview().offset(20)
                    make.right.equalToSuperview().offset(-20)
                    make.top.equalTo(titlelabel.snp.bottom).offset(7)
                }
                bgView.snp.remakeConstraints { make in
                    make.left.equalToSuperview().offset(20)
                    make.right.equalToSuperview().offset(-20)
                    make.top.equalTo(noLabel.snp.bottom).offset(16)
                    make.bottom.equalTo(-10)
                }
                
                unavailableLabel.snp.remakeConstraints { make in
                    make.top.left.equalToSuperview().offset(12)
                    make.right.bottom.equalToSuperview().offset(-12)
                }
                if self.materialModel.status == 0 || self.materialModel.status == 1 {
                    bgView.snp.remakeConstraints { make in
                        make.left.equalToSuperview().offset(20)
                        make.right.equalToSuperview().offset(-20)
                        make.top.equalTo(tipsLabel.snp.bottom).offset(16)
                        make.bottom.equalTo(-10)
                    }
                }
            }
            return view
        }
        view.frame = CGRect(x: 0, y: 0, width: KScreenWidth, height: 0.01)
        return view
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 0 { // 模板列表
            if 0 <= indexPath.row && indexPath.row < templateArr.count {
                let path = templateArr[indexPath.row]
                if !path.url.isEmpty {
                    self.previewFileTool.openXLSXRemoteFile(urlString: path.url, fileName: "预览")
                }
            }
             
        } else if indexPath.section == 1 { // 证件列表
            if 0 <= indexPath.row && indexPath.row < items.count {
                let cer = items[indexPath.row]
                if !cer.url.isEmpty {
                    print(cer.url)
                    self.viewModel.getPublicImageUrl(cer.url) { success, _ in
                        if let success = success {
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: cer.name)
                        }
                    }
                }
            }
        }
    }
    
    @objc func dismissed() {
        renameInputView.textField.resignFirstResponder()
    }
}

extension YHResignUploadDocDetailViewController {
    
    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
            if clickInputViewIndex == 0 {
                let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileRenameInputView.height)
                
                if !isKeyboardShow {
                    IQKeyboardManager.shared.isEnabled = true
                }
                
                self.renameInputView.snp.updateConstraints { make in
                    make.bottom.equalToSuperview().offset(bottomMargin)
                }
            } else {
                let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileExplainReasonInputView.height)
                
                if !isKeyboardShow {
                    IQKeyboardManager.shared.isEnabled = true
                }
                
                self.reasonInputView.snp.updateConstraints { make in
                    make.bottom.equalToSuperview().offset(bottomMargin)
                }
            }
            
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}

extension YHResignUploadDocDetailViewController {
    
    func requestMaterialDetail() {
        viewModel.getUploadDocDetail(id: id) {[weak self] _, _ in
            guard let self = self else { return }
            self.materialModel = self.viewModel.mainModel
            if self.materialModel.status == 0 || self.materialModel.status == 1 {
                self.uploadBtn.isHidden = true
            } else {
                self.uploadBtn.isHidden = false
            }
            templateArr = self.viewModel.mainModel.template_list
            items = self.viewModel.mainModel.file_list
            self.tableView.reloadData()
        }
    }
    
}
