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

import UIKit
import IQKeyboardManagerSwift

class YHWorkExperienceViewController: YHBaseViewController {
    var stepView: YHStepView!
    var bottomView: YHBottomNextView!
    var tableView: UITableView!
    var viewModel: YHWorkExperienceViewModel!
    var baseDataSource: [YHSectionWorkExperienceModel]?
    var introductionDataSource: [YHWorkExperienceProjectModel]?
    var fileDataSource: [YHWorkExperienceFileModel]?
    var workExperienceID: String?
    var orderID: Int = 0
    var isMore: Bool = false
    var isShowPrompt: Bool = false
    var isShowMessageSelect: Bool = true
    var selectEditItem = YHWorkExperienceFileModel()
    var renameInputView: YHFileRenameInputView = {
        let view = YHFileRenameInputView.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
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHWorkExperienceViewModel()
        gk_navTitle = "工作经验信息填写"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        
        
        setView()
        getData()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardDidShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardDidHideNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
        // Do any additional setup after loading the view.
        renameInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            if var text = text, let dataSorce = fileDataSource {
                // 重命名
                self.renameInputView.isHidden = true
                text = text + "." + getFileSuffixName(selectEditItem.fileUrl)
                for item in dataSorce {
                    if item.fileUrl == selectEditItem.fileUrl {
                        item.fileName = text
                    }
                }
                self.viewModel.mainModel.file = self.fileDataSource ?? []
                self.viewModel.saveWorkDetail(0, orderID: self.orderID, callBackBlock: {flag, error in
                })
                self.tableView.reloadData()
            }
        }
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if notification.userInfo != nil {
            if stepView.currentIndex == 4 || stepView.currentIndex == 3 {
                guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else {return }
                
                let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
                self.blackMaskView.isHidden = !isKeyboardShow
                let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : YHFileRenameInputView.height)
                
                if !isKeyboardShow {
                    IQKeyboardManager.shared.enable = true
                }
                
                self.renameInputView.snp.updateConstraints { make in
                    make.bottom.equalToSuperview().offset(bottomMargin)
                }
                self.view.setNeedsLayout()
                self.view.layoutIfNeeded()
            }
        }
    }
    
    func getData() {
        viewModel.requestWorkExample { success, error in
            
        }
        viewModel.requestWorkDetail(workExperienceID ?? "") {[weak self] success, error in
            guard let self = self else { return }
            self.stepView.currentIndex = self.viewModel.mainModel.step
            self.stepView.maxIndex = self.viewModel.mainModel.step
            self.updateDataSource()
            if self.viewModel.mainModel.is_project_introduction == 1 {
                self.stepView.dataSource = ["基本信息", "工作职责", "工作亮点", "项目介绍", "简历/工作总结"]
            } else {
                self.stepView.dataSource = ["基本信息", "工作职责", "工作亮点", "简历/工作总结"]
            }
            self.viewModel.requestWorkInfoProject("\(self.viewModel.mainModel.id )") {[weak self] success, error in
                guard let self = self else { return }
                self.introductionDataSource = success
                self.fileDataSource = self.viewModel.mainModel.file
                self.updateDataSource()
            }
        }
        updateDataSource()
    }
    
    func updateDataSource() {
        if self.stepView.currentIndex == 0 {
            self.baseDataSource = self.viewModel.getBaseDataSource(isShowPrompt)
        }
        if (self.viewModel.mainModel.is_project_introduction == 1 && self.stepView.currentIndex == 4) || (self.viewModel.mainModel.is_project_introduction != 1 && self.stepView.currentIndex == 3) {
            bottomView.nextButton.setTitle("提交", for: .normal)
        } else {
            bottomView.nextButton.setTitle("下一步", for: .normal)
        }
        self.tableView.reloadData()
    }
    
    func setView() {
        stepView = {
            let step = YHStepView()
            step.dataSource = ["基本信息", "工作职责", "工作亮点", "简历/工作总结"]
            step.contentSize = CGSize(width: KScreenWidth * 1.2, height: 104)
            step.showsHorizontalScrollIndicator = false
            step.showsVerticalScrollIndicator = false
            step.block = { [weak self] (index) in
                guard let self = self else { return }
                self.updateDataSource()
            }
            return step
        }()
        view.addSubview(stepView)
        stepView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.left.right.equalTo(view)
            make.height.equalTo(104)
        }
        
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHWorkExperienceTableViewCell.self)
            tableView.register(cellWithClass: YHWorkResponsibilitiesTableViewCell.self)
            tableView.register(cellWithClass: YHWorkHighlightsTableViewCell.self)
            tableView.register(cellWithClass: YHWorkIntroductionTableViewCell.self)
            tableView.register(cellWithClass: YHWorkMessageSelectTableViewCell.self)
            tableView.register(cellWithClass: YHWorkFileSyncTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + YHStepView.height)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.bottom.equalTo(view)
        }
        
        bottomView = {
            let bottom = YHBottomNextView()
            bottom.nextblock = { [weak self] in
                bottom.nextButton.isEnabled = false
                guard let self = self else { return }
                if self.viewModel.isCanNext(self.stepView.currentIndex) {
                    self.viewModel.mainModel.step = self.stepView.currentIndex
                    self.viewModel.saveWorkDetail(1, orderID: self.orderID, callBackBlock: {[weak self] flag, error in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            YHHUD.hideFlashMessage()
                            if self.stepView.currentIndex == 4 || (self.stepView.currentIndex == 3 && self.viewModel.mainModel.is_project_introduction == 0) {
                                YHHUD.flash(message: "提交成功")
                                self.navigationController?.popViewController()
                            } else {
                                self.stepView.currentIndex = self.stepView.currentIndex + 1
                                self.updateDataSource()
                            }
                        }
                    })
                } else {
                    bottom.nextButton.isEnabled = true
                    self.isShowPrompt = true
                    self.updateDataSource()
                    YHHUD.flash(message: "您还有信息未填写")
                }
            }
            bottom.saveBlock = { [weak self] in
                guard let self = self else { return }
                self.viewModel.saveWorkDetail(0, orderID: self.orderID, callBackBlock: {[weak self] flag, error in
                    guard let self = self else { return }
                    if let error = error {
                        YHHUD.flash(message: error.errorMsg )
                    } else {
                        YHHUD.flash(message: "保存成功")
                    }
                })
            }
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        bottomView.layoutIfNeeded()
        bottomView.nextButton.addYinHeGradualLayer()
        view.addSubview(blackMaskView)
        view.addSubview(renameInputView)
        renameInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHFileRenameInputView.height)
            make.bottom.equalToSuperview().offset(YHFileRenameInputView.height)
        }
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
        if stepView.currentIndex != 0 {
            // 当键盘将要显示时调用此函数
            stepView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.left.right.equalTo(view)
                make.height.equalTo(0)
            }
            stepView.isHidden = true
            tableView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
                make.left.right.bottom.equalTo(view)
            }
        }
    }
     
    @objc func keyboardWillHide(_ notification: Notification) {
        if stepView.currentIndex != 0 {
            // 当键盘将要隐藏时调用此函数
            stepView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
                make.left.right.equalTo(view)
                make.height.equalTo(104)
            }
            stepView.isHidden = false
            tableView.snp.remakeConstraints { make in
                make.top.equalTo(k_Height_NavigationtBarAndStatuBar + YHStepView.height)
                make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
                make.left.right.bottom.equalTo(view)
            }
        }
    }
    
    func showDeleteAlert(_ model: YHWorkExperienceProjectModel) {
        YHCommonAlertView.show("", "确定要删除该项目介绍吗？", "取消", "确认") {[weak self] in
            guard let self = self else { return }
            self.viewModel?.requestDeleteWorkExperienceProject("\(model.id ?? 0)", callBackBlock: {[weak self] success, error in
                guard let self = self else { return }
                self.getData()
            })
        }
    }
    
    func showDeleteAlert(_ model: YHWorkExperienceFileModel) {
        YHCommonAlertView.show("", "确定要删除吗？", "取消", "确认") {[weak self] in
            guard let self = self else { return }
            for i in 0..<(self.fileDataSource?.count ?? 0) {
                let data = self.fileDataSource?[i]
                if data?.fileName == model.fileName {
                    self.fileDataSource?.remove(at: i)
                    self.tableView.reloadData()
                    self.viewModel.mainModel.file = self.fileDataSource ?? []
                    return
                }
            }
            
        }
    }
    
    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 = YHWorkExperienceFileModel()
                    model.fileUrl = successUrl
                    model.fileName = fileName
                    model.uploadedAt = formattedDate
                    self.fileDataSource?.append(model)
                    self.viewModel.mainModel.file = self.fileDataSource ?? []
                    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: "识别文件失败")
        }
    }
    
    func uploadImage(_ img: UIImage, imageName:String, callBack:((Bool, String)->())?) {
        // 先OSS上传得到URL
        self.viewModel.uploadImage(img) {
            [weak self] url, error in
            guard self != nil else { return }
            if let url = url, !url.isEmpty {
                callBack?(true, url)
                return
            }
            callBack?(false, "")
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func getFileNameWithoutSuffix(_ string: String) -> String {
        if string.isEmpty {
            return string
        }
        if !string.contains(".") {
            return string
        }
        if !string.pathExtension.isEmpty {
          let fileName = (string as NSString).deletingPathExtension
          return fileName
        }
        return ""
    }
    
    func getFileSuffixName(_ string: String)->String {
        let res1 = string.pathExtension.lowercased()
        if !res1.isEmpty {
            return res1
        }
        return ""
    }
    
    @objc func dismissed() {
        renameInputView.textField.resignFirstResponder()
    }
}

extension YHWorkExperienceViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if stepView.currentIndex == 1 || stepView.currentIndex == 2 {
            return 1
        }
        if stepView.currentIndex == 3 {
            return 1
        }
        if stepView.currentIndex == 4 {
            return 1
        }
        return baseDataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if stepView.currentIndex == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkResponsibilitiesTableViewCell.self)
            cell.dataSource = viewModel.mainModel.wduty
            cell.exampleBlock = {[weak self] in
                guard let self = self else { return }
                let mainVc = YHWorkExampleViewController()
                mainVc.dataSource = self.viewModel.exampleModels
                mainVc.type = .wduty
                mainVc.exampleBlock = {[weak self] message in
                    guard let self = self else { return }
                    cell.dataSource = message
                    self.viewModel.updateWduty(message)
                }
                let vc = UINavigationController(rootVC: mainVc)
                vc.modalPresentationStyle = .pageSheet
                self.navigationController?.present(vc, animated: true)
            }
            cell.messageBlock = {[weak self] message in
                self?.viewModel.updateWduty(message)
            }
            cell.photoBlock = {[weak self] in
                guard let self = self else { return }
                YHImagePickerView.show() {[weak self] image in
                    guard let self = self else { return }
                    let clipperVC = YHImageClipperViewController()
                    
                    clipperVC.setBaseImg(image, resultImgSize: CGSize(width: image.size.width, height: image.size.height), type: .Stay)
                    clipperVC.successClippedHandler = {[weak self] result in
                        guard let self = self else { return }
                        self.viewModel.mainModel.wduty = result
                        cell.dataSource = viewModel.mainModel.wduty
                    }
                    self.navigationController?.pushViewController(clipperVC, animated: true)
                }
            }
            return cell
        } else if stepView.currentIndex == 2 {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkHighlightsTableViewCell.self)
            cell.dataSource = viewModel.mainModel.highlights
            cell.detailSwitch.isOn = viewModel.mainModel.is_project_introduction == 1
            cell.exampleBlock = {[weak self] in
                guard let self = self else { return }
                let mainVc = YHWorkExampleViewController()
                mainVc.dataSource = self.viewModel.exampleModels
                mainVc.type = .highlight
                mainVc.exampleBlock = {[weak self] message in
                    guard let self = self else { return }
                    cell.dataSource = message
                    self.viewModel.updateHighlights(message)
                }
                let vc = UINavigationController(rootVC: mainVc)
                vc.modalPresentationStyle = .pageSheet
                self.navigationController?.present(vc, animated: true)
            }
            cell.messageBlock = {[weak self] message in
                self?.viewModel.updateHighlights(message)
            }
            cell.switchBlock = {[weak self] isOn in
                self?.viewModel.updateIsProjectIntroduction(isOn: isOn)
                if isOn {
                    self?.stepView.dataSource = ["基本信息", "工作职责", "工作亮点", "项目介绍", "简历/工作总结"]
                } else {
                    self?.stepView.dataSource = ["基本信息", "工作职责", "工作亮点", "简历/工作总结"]
                }
            }
            cell.photoBlock = {[weak self] in
                guard let self = self else { return }
                YHImagePickerView.show() {[weak self] image in
                    guard let self = self else { return }
                    let clipperVC = YHImageClipperViewController()
                    clipperVC.setBaseImg(image, resultImgSize: CGSize(width: image.size.width, height: image.size.height), type: .Stay)
                    clipperVC.successClippedHandler = {[weak self] result in
                        guard let self = self else { return }
                        self.viewModel.mainModel.highlights = result
                        cell.dataSource = viewModel.mainModel.highlights
                    }
                    self.navigationController?.pushViewController(clipperVC, animated: true)
                }
            }
            return cell
        } else if stepView.currentIndex == 3 {
            if self.viewModel.mainModel.is_project_introduction == 1 {
                let cell = tableView.dequeueReusableCell(withClass: YHWorkIntroductionTableViewCell.self)
                cell.dataSource = introductionDataSource
                if isMore {
                    cell.more()
                } else {
                    cell.cannal()
                }
                cell.clickBlock = {[weak self] model in
                    guard let self = self else { return }
                    let vc = YHWorkIntroductionViewController()
                    vc.dataSource = model
                    vc.workModel = self.viewModel.mainModel
                    vc.saveBlock = {[weak self] in
                        guard let self = self else { return }
                        self.getData()
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                cell.deleteBlock = {[weak self] model in
                    guard let self = self else { return }
                    self.showDeleteAlert(model)
                }
                cell.isMoreBlock = {[weak self] isMore in
                    guard let self = self else { return }
                    self.isMore = isMore
                }
                cell.addIntroductionBlock = {[weak self] in
                    guard let self = self else { return }
                    let vc = YHWorkIntroductionViewController()
                    vc.workModel = self.viewModel.mainModel
                    vc.saveBlock = {[weak self] in
                        guard let self = self else { return }
                        self.getData()
                    }
                    self.navigationController?.pushViewController(vc, animated: true)
                }
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withClass: YHWorkFileSyncTableViewCell.self)
                cell.dataSource = fileDataSource
                cell.addIntroductionBlock = { [weak self] in
                    guard let self = self else { return }
                    let count = self.viewModel.mainModel.file.count
                    if count >= 99 {
                        YHHUD.flash(message: "最多上传99个图片或文件")
                        return
                    }
                    var maxCount = 99 - count
                    if maxCount > 9 {
                        maxCount = 9
                    }
                    let sheetView = YHCertificateUploadSheetView.sheetView()
                    sheetView.maxSelectCount = maxCount
                    sheetView.uploadFilesBlock = {
                        [weak self] fileUrl in
                        guard let self = self else { return }
                        print(fileUrl)
                        uploadFile(fileUrl)
                    }
                    sheetView.uploadImageBlock = {
                        [weak self] imgArr in
                        guard let self = self else { return }
                        let group = DispatchGroup()
                        var successArr:[String] = []
                        var failArr:[YHSelectImageItem] = []

                        YHHUD.show(.progress(message: "上传中..."))
                        for item in imgArr {
                            if let image = item.data {
                                group.enter()
                                uploadImage(image, imageName:item.name) {
                                    success, url  in
                                    if success {
                                        successArr.append(url)
                                    } else {
                                        failArr.append(item)
                                    }
                                    group.leave()
                                }
                            }
                        }
                        
                        // 等待所有任务完成
                        group.notify(queue: .main) {
                            YHHUD.hide()
                            // 所有任务完成，回到主线程继续执行
                            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 = YHWorkExperienceFileModel()
                                    model.fileUrl = item
                                    model.fileName = "\(UInt64(timestamp))" + ".jpg"
                                    model.uploadedAt = formattedDate
                                    self.fileDataSource?.append(model)
                                    self.viewModel.mainModel.file = self.fileDataSource ?? []
                                }
                                self.tableView.reloadData()
                            } else {
                                YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
                            }
                            
                        }
                    }
                    sheetView.show()
                }
                cell.experienceListBlock = {[weak self] model, type in
                    guard let self = self else { return }
                    if type == .delete {
                        
                        let items = [YHCertificateEditItem(type:.rename, title:"重命名"),
                                     YHCertificateEditItem(type:.preview, title:"预览"),
                                     YHCertificateEditItem(type:.delete, title:"删除"),
                                     YHCertificateEditItem(type:.cancel, title:"取消")]
                        YHCertificateEditSheetView.sheetView(items:items) {
                            [weak self] editType in
                            guard let self = self else { return }
                            if editType == .rename {
                                self.selectEditItem = model
                                var name = getFileNameWithoutSuffix(model.fileName)
                                if name.count > 30 {
                                    name = name[safe: ..<30]!
                                }
                                renameInputView.textField.text = name
                                renameInputView.textField.becomeFirstResponder()
                            }
                            if editType == .preview {
                                if model.fileUrl.isEmpty == false {
                                    let vc = YHImageViewController()
                                    vc.imgString = model.fileUrl
                                    UIViewController.current?.navigationController?.pushViewController(vc)
                                }
                                
                            }
                            if editType == .delete {
                                self.showDeleteAlert(model)
                            }
                        }.show()
                    } else {
                        if model.fileUrl.isEmpty == false {
                            let vc = YHImageViewController()
                            vc.imgString = model.fileUrl
                            UIViewController.current?.navigationController?.pushViewController(vc)
                        }
                    }
                }
                cell.selectIntroductionBlock = { [weak self] in
                    guard let self = self else { return }
                    YHSelectFileSheetView.show(orderID: self.orderID) { [weak self] models in
                        guard let self = self else { return }
                        for item in models {
                            self.fileDataSource?.append(item)
                            self.viewModel.mainModel.file = self.fileDataSource ?? []
                        }
                        self.tableView.reloadData()
                        if models.count != 0 {
                            YHHUD.flash(message: "同步成功")
                        }
                    }
                }
                return cell
            }
        } else if stepView.currentIndex == 4 {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkFileSyncTableViewCell.self)
            cell.dataSource = fileDataSource
            cell.addIntroductionBlock = { [weak self] in
                guard let self = self else { return }
                let count = self.viewModel.mainModel.file.count
                if count >= 99 {
                    YHHUD.flash(message: "最多上传99个图片或文件")
                    return
                }
                var maxCount = 99 - count
                if maxCount > 9 {
                    maxCount = 9
                }
                let sheetView = YHCertificateUploadSheetView.sheetView()
                sheetView.maxSelectCount = maxCount
                sheetView.uploadFilesBlock = {
                    [weak self] fileUrl in
                    guard let self = self else { return }
                    print(fileUrl)
                    uploadFile(fileUrl)
                }
                sheetView.uploadImageBlock = {
                    [weak self] imgArr in
                    guard let self = self else { return }
                    let group = DispatchGroup()
                    var successArr:[String] = []
                    var failArr:[YHSelectImageItem] = []

                    YHHUD.show(.progress(message: "上传中..."))
                    for item in imgArr {
                        if let image = item.data {
                            group.enter()
                            uploadImage(image, imageName:item.name) {
                                success, url  in
                                if success {
                                    successArr.append(url)
                                } else {
                                    failArr.append(item)
                                }
                                group.leave()
                            }
                        }
                    }
                    
                    // 等待所有任务完成
                    group.notify(queue: .main) {
                        YHHUD.hide()
                        // 所有任务完成，回到主线程继续执行
                        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 = YHWorkExperienceFileModel()
                                model.fileUrl = item
                                model.fileName = "\(UInt64(timestamp))" + ".jpg"
                                model.uploadedAt = formattedDate
                                self.fileDataSource?.append(model)
                                self.viewModel.mainModel.file = self.fileDataSource ?? []
                            }
                            self.tableView.reloadData()
                        } else {
                            YHHUD.flash(message: "\(successArr.count)张照片上传成功\n\(failArr.count)张照片上传失败")
                        }
                        
                    }
                }
                sheetView.show()
            }
            cell.experienceListBlock = {[weak self] model, type in
                guard let self = self else { return }
                if type == .delete {
                    let items = [YHCertificateEditItem(type:.rename, title:"重命名"),
                                 YHCertificateEditItem(type:.preview, title:"预览"),
                                 YHCertificateEditItem(type:.delete, title:"删除"),
                                 YHCertificateEditItem(type:.cancel, title:"取消")]
                    YHCertificateEditSheetView.sheetView(items:items) {
                        [weak self] editType in
                        guard let self = self else { return }
                        if editType == .rename {
                            self.selectEditItem = model
                            var name = getFileNameWithoutSuffix(model.fileName)
                            if name.count > 30 {
                                name = name[safe: ..<30]!
                            }
                            renameInputView.textField.text = name
                            renameInputView.textField.becomeFirstResponder()
                        }
                        if editType == .preview {
                            if model.fileUrl.isEmpty == false {
                                let vc = YHImageViewController()
                                vc.imgString = model.fileUrl
                                UIViewController.current?.navigationController?.pushViewController(vc)
                            }
                        }
                        if editType == .delete {
                            self.showDeleteAlert(model)
                        }
                    }.show()
                } else {
//                    let vc = YHImageViewController()
//                    vc.imgString = model.fileUrl
//                    UIViewController.current?.navigationController?.pushViewController(vc)
                    
                    
                    if model.fileUrl.isEmpty == false {
                        let vc = YHImageViewController()
                        vc.imgString = model.fileUrl
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    }
                }
            }
            cell.selectIntroductionBlock = { [weak self] in
                guard let self = self else { return }
                YHSelectFileSheetView.show(orderID: self.orderID) { [weak self] models in
                    guard let self = self else { return }
                    for item in models {
                        self.fileDataSource?.append(item)
                        self.viewModel.mainModel.file = self.fileDataSource ?? []
                    }
                    self.tableView.reloadData()
                    if models.count != 0 {
                        YHHUD.flash(message: "同步成功")
                    }
                }
            }
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkExperienceTableViewCell.self)
            cell.country = self.viewModel.mainModel.location.country
            cell.dataSource = baseDataSource?[indexPath.row]
            cell.workExperienceBlock = {[weak self] model in
                guard let self = self else { return }
                self.viewModel.updateModel(model)
                let id = model.id
                if id != .id1 && id != .id3 && id != .id4 && id != .id7 && id != .id8 && id != .id12 && id != .id14 && id != .id16 && id != .id17 && id != .id18 {
                    self.updateDataSource()
                }
            }
            cell.companyBlock = {[weak self] company in
                guard let self = self else { return }
                self.viewModel.updateModel(company)
                self.updateDataSource()
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if stepView.currentIndex == 1 || stepView.currentIndex == 2 {
            return KScreenHeight - k_Height_NavigationtBarAndStatuBar - YHStepView.height - k_Height_safeAreaInsetsBottom() - 64
        } else if stepView.currentIndex == 3 {
            if self.viewModel.mainModel.is_project_introduction == 1 {
                let number = introductionDataSource?.count ?? 0
                return CGFloat(76 * number + 150)
            } else {
                let count = fileDataSource?.count ?? 0
                return CGFloat(69 * count + 171)
            }
        } else if stepView.currentIndex == 4 {
            let count = fileDataSource?.count ?? 0
            return CGFloat(69 * count + 171)
        } else {
            let array = baseDataSource?[indexPath.row].models ?? []
            var h = 0
            for i in 0..<array.count {
                let data = array[i]
                let message = data.message ?? ""
                let isShow = data.isShowPrompts ?? false
                if data.id == .id3 || data.id == .id4 || data.id == .id18 {
                    h = h + 132
                } else if data.id == .id13 {
                    h = h + 72
                } else {
                    h = h + 52
                }
                if isShow && message.count == 0 {
                    h = h + 20
                }
            }
            return CGFloat(h + 52 + 14)
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 7
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}
