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

import UIKit
import IQKeyboardManagerSwift
import AttributedString

class YHWorkExperienceViewController: YHBaseViewController {
    var stepView: YHStepView!
    var bottomView: YHBottomNextView!
    var tableView: UITableView!
    var viewModel: YHWorkExperienceViewModel!
    var baseDataSource: [YHSectionWorkExperienceModel]?
    var fileDataSource: [YHWorkExperienceFileModel]?
    var workId: Int = 0
    var orderID: Int = 0
    var isMore: Bool = false
    var isShowPrompt: Bool = false
    var isKeyboardShow: Bool = false
    var selectEditItem = YHWorkExperienceFileModel()
    var fileMessageArray: [String] = ["签字盖章的推荐信", "盖章的工作证明+签字的推荐信", "其他证明(退工单或合同+社保等证明)", "以上均不能提供"]
    var renameInputView: YHFileRenameInputView = {
        let view = YHFileRenameInputView.inputView(defalutText: "请输入名称")
        return view
    }()
    lazy var previewFileTool:YHFilePreviewTool = {
       let tool = YHFilePreviewTool(targetVC: self)
       return tool
    }()
    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 {
                // 重命名
                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(workId: workId, callBackBlock: {flag, error in
                })
                self.tableView.reloadData()
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if workId == 0 {
            return
        }
        viewModel.requestWorkPositionList("\(orderID)", "\(workId)") {[weak self]  success, error in
            guard let self = self else { return }
            self.updateDataSource()
        }
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if notification.userInfo != nil {
            if 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.isEnabled = 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
            
        }
        if workId == 0 {
            self.stepView.currentIndex = 0
            self.stepView.maxIndex = 0
            self.updateDataSource()
            return
        }
        viewModel.requestWorkStep("\(orderID)", "\(workId)") {[weak self] success, error in
            guard let self = self else { return }
            if self.viewModel.stepModel.step < 3 {
                self.stepView.currentIndex = self.viewModel.stepModel.step
                self.stepView.maxIndex = self.viewModel.stepModel.step
            } else {
                self.stepView.currentIndex = 3
                self.stepView.maxIndex = 3
            }
            self.stepView.dataSource = ["基本信息", "工作职责", "工作亮点", "简历/工作总结"]
            viewModel.requestWorkPositionList("\(orderID)", "\(workId)") {[weak self]  success, error in
                guard let self = self else { return }
                self.updateDataSource()
            }
            viewModel.requestworkDutyDetail("\(workId)") {[weak self] success, error in
                guard let self = self else { return }
                self.updateDataSource()
            }
            viewModel.requestWorkHighlightsDetail("\(workId)") {[weak self] success, error in
                guard let self = self else { return }
                self.updateDataSource()
            }
            viewModel.requestWorkDetail("\(orderID)", "\(workId)") {[weak self] success, error in
                guard let self = self else { return }
                self.updateDataSource()
            }
            self.viewModel.requestWorkInfoProject("\(workId)") {[weak self] success, error in
                guard let self = self else { return }
                self.fileDataSource = self.viewModel.mainModel.file
                self.updateDataSource()
            }
        }
    }
    
    func updateDataSource() {
        if self.stepView.currentIndex == 0 {
            self.baseDataSource = self.viewModel.getBaseDataSource(isShowPrompt)
        }
        if  self.stepView.currentIndex == 3 {
            bottomView.nextButton.setTitle("提交", for: .normal)
        } else {
            bottomView.nextButton.setTitle("下一步", for: .normal)
        }
        self.tableView.reloadData()
    }
    
    func getTextWithType(type: Int) -> ASAttributedString  {
        
        if type ==  0 {
           return .init("签字盖章的推荐信", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor))
        }
        if type ==  1 {
            let a:ASAttributedString = .init("盖章的工作证明+签字的推荐信", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor))
           return a
        }
        if type ==  2 {
            let a:ASAttributedString = .init("其他证明(退工单或合同+社保等证明) \n", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor))
            let b: ASAttributedString = .init("(此类文件加分以港府审批为准)", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor(hex: 0x8993a2)))
           return a + b
        }
        if type ==  3 {
            let a:ASAttributedString = .init("以上均不能提供\n", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor))
            let b: ASAttributedString = .init("(或将导致您的该段工作经验", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor(hex: 0x8993a2)))
            let c: ASAttributedString = .init("不被认可不予加分", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.failColor))
            let d: ASAttributedString = .init("，请尽可能准备以上材料并修改此选项)", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor(hex: 0x8993a2)))
           return a + b + c + d
        }
        return .init("", .font(UIFont.PFSC_R(ofSize:14)),.foreground(UIColor.mainTextColor(alpha: 0.5)))
    }
    
    func getTipsWithType() -> [ASAttributedString] {
        return [self.getTextWithType(type: 0),
                self.getTextWithType(type: 1),
                self.getTextWithType(type: 2),
                self.getTextWithType(type: 3)]
    }
    
    func getSelectCompany() -> Int {
        return fileMessageArray.firstIndex(where: {$0 == viewModel.mainModel.work_certificate}) ?? 5
    }
    
    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: YHWorkMessageSelectTableViewCell.self)
            tableView.register(cellWithClass: YHWorkFileSyncTableViewCell.self)
            tableView.register(cellWithClass: YHWorkExperiencePositionTableViewCell.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) {
                    if self.stepView.currentIndex == 0 {
                        if self.viewModel.positionList.count == 0 {
                            self.isShowPrompt = true
                            tableView.reloadData()
                            YHHUD.flash(message: "至少需要新增一个职位")
                            bottom.nextButton.isEnabled = true
                            return
                        }
                        for item in self.viewModel.positionList {
                            if item.missing_item_num > 0 {
                                self.isShowPrompt = true
                                tableView.reloadData()
                                YHHUD.flash(message: "您的职位未全部填写完成，请先填写完成再提交")
                                bottom.nextButton.isEnabled = true
                                return
                            }
                        }
                        self.viewModel.saveWorkData(orderID, workId: workId) {[weak self]  success, error in
                            guard let self = self else { return }
                            bottom.nextButton.isEnabled = true
                            if let error = error {
                                YHHUD.flash(message: error.errorMsg )
                            } else {
                                self.stepView.currentIndex = self.stepView.currentIndex + 1
                                self.updateDataSource()
                            }
                        }
                    } else if self.stepView.currentIndex == 1 {
                        self.viewModel.saveWorkDuty(workId: workId) {[weak self] success, error in
                            guard let self = self else { return }
                            bottom.nextButton.isEnabled = true
                            if let error = error {
                                YHHUD.flash(message: error.errorMsg )
                            } else {
                                self.stepView.currentIndex = self.stepView.currentIndex + 1
                                self.updateDataSource()
                            }
                        }
                    } else if self.stepView.currentIndex == 2 {
                        self.viewModel.saveWorkHighlights(workId: workId) {[weak self] success, error in
                            guard let self = self else { return }
                            bottom.nextButton.isEnabled = true
                            if let error = error {
                                YHHUD.flash(message: error.errorMsg )
                            } else {
                                self.stepView.currentIndex = self.stepView.currentIndex + 1
                                self.updateDataSource()
                            }
                        }
                    } else {
                        self.viewModel.saveWorkDetail(workId: workId, 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 == 3 {
                                    YHHUD.flash(message: "提交成功")
                                    self.navigationController?.popViewController()
                                } else {
                                    self.stepView.currentIndex = self.stepView.currentIndex + 1
                                }
                            }
                        })
                    }
                } else {
                    bottom.nextButton.isEnabled = true
                    self.isShowPrompt = true
                    self.updateDataSource()
                    YHHUD.flash(message: "您还有信息未填写")
                }
            }
            bottom.saveBlock = { [weak self] in
                guard let self = self else { return }
                if self.stepView.currentIndex == 0 {
                    self.viewModel.saveWorkData(orderID, workId: workId, 0) {[weak self]  success, error in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            YHHUD.flash(message: "保存成功")
                        }
                    }
                } else if self.stepView.currentIndex == 1 {
                    self.viewModel.saveWorkDuty(workId: workId, 0) {[weak self] success, error in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            YHHUD.flash(message: "保存成功")
                        }
                    }
                } else if self.stepView.currentIndex == 2 {
                    self.viewModel.saveWorkHighlights(workId: workId, 0) {[weak self] success, error in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            self.stepView.currentIndex = self.stepView.currentIndex + 1
                            self.updateDataSource()
                        }
                    }
                } else {
                    self.viewModel.saveWorkDetail(workId: workId, 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.currentIndex != 3 {
            // 当键盘将要显示时调用此函数
            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)
            }
            isKeyboardShow = true
            let rightButtonItem = UIBarButtonItem(title: "下一步", style: .plain, target: self, action: #selector(nextStep))
            rightButtonItem.setTitleTextAttributes([.foregroundColor: UIColor.brandMainColor], for: .normal)
            rightButtonItem.setTitleTextAttributes([.foregroundColor: UIColor.brandMainColor], for: .highlighted)
            gk_navRightBarButtonItem = rightButtonItem
            gk_navItemRightSpace = 16
        }
    }
     
    @objc func keyboardWillHide(_ notification: Notification) {
        if stepView.currentIndex != 0 && stepView.currentIndex != 3 {
            // 当键盘将要隐藏时调用此函数
            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)
            }
            isKeyboardShow = false
            gk_navRightBarButtonItems = []
        }
    }
    
    @objc func nextStep() {
        self.view.endEditing(true)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
            if self.viewModel.isCanNext(self.stepView.currentIndex) {
                if self.stepView.currentIndex == 1 {
                    self.viewModel.saveWorkDuty(workId: self.workId) {[weak self] success, error in
                        guard let self = self else { return }
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            self.stepView.currentIndex = self.stepView.currentIndex + 1
                            self.updateDataSource()
                        }
                    }
                } else if self.stepView.currentIndex == 2 {
                    self.viewModel.saveWorkHighlights(workId: self.workId) {[weak self] success, error in
                        guard let self = self else { return }
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            self.stepView.currentIndex = self.stepView.currentIndex + 1
                            self.updateDataSource()
                        }
                    }
                }
            } else {
                self.isShowPrompt = true
                self.updateDataSource()
                YHHUD.flash(message: "您还有信息未填写")
            }
        }
    }
    
    func showDeleteAlert(_ model: YHWorkExperiencePositionModel) {
        YHCommonAlertView.show("", "确定要删除该职位信息吗？", "取消", "确认") {[weak self] in
            guard let self = self else { return }
            self.viewModel?.requestDeleteWorkPosition(model, callBackBlock: {[weak self] success, error in
                guard let self = self else { return }
                self.viewModel.requestWorkPositionList("\(orderID)", "\(workId)") {[weak self]  success, error in
                    guard let self = self else { return }
                    self.updateDataSource()
                }
            })
        }
    }
    
    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 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if stepView.currentIndex == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkResponsibilitiesTableViewCell.self)
            cell.dataSource = viewModel.dutyModel.work_duty
            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.dutyModel.work_duty = result
                        cell.dataSource = viewModel.dutyModel.work_duty
                    }
                    self.navigationController?.pushViewController(clipperVC, animated: true)
                }
            }
            return cell
        } else if stepView.currentIndex == 2 {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkHighlightsTableViewCell.self)
            cell.dataSource = viewModel.helightModel.work_highlights
            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.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.helightModel.work_highlights = result
                        cell.dataSource = viewModel.helightModel.work_highlights
                    }
                    self.navigationController?.pushViewController(clipperVC, animated: true)
                }
            }
            return cell
        } else if stepView.currentIndex == 3 {
            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.maxSelectImageCount = 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 {
                                self.viewModel.getPublicImageUrl(model.fileUrl) { success, error in
                                    if let success = success {
                                        self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName:model.fileName)
                                    }
                                }
                            }
                        }
                        if editType == .delete {
                            self.showDeleteAlert(model)
                        }
                    }.show()
                } else {
                    
                    
                    if model.fileUrl.isEmpty == false {
                        self.viewModel.getPublicImageUrl(model.fileUrl) { success, error in
                            if let success = success {
                                self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName:model.fileName)
                            }
                        }
                    }
                }
            }
            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 indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withClass: YHWorkExperienceTableViewCell.self)
                cell.orderId = orderID
                cell.workId = workId
                cell.selectDataSource = getTipsWithType()
                cell.selectItem = getSelectCompany()
                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 {
                        self.updateDataSource()
                    }
                }
                cell.selectBlock = {[weak self] index in
                    guard let self = self else { return }
                    self.viewModel.mainModel.work_certificate = fileMessageArray[index.first ?? 0]
                }
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withClass: YHWorkExperiencePositionTableViewCell.self)
                cell.showPrompt = isShowPrompt
                cell.dataSource = self.viewModel.positionList
                if isMore {
                    cell.more()
                } else {
                    cell.cannal()
                }
                cell.clickBlock = {[weak self] model in
                    guard let self = self else { return }
                    let vc = YHWorkExperiencePositionViewViewController()
                    vc.workID = model.work_id
                    vc.orderID = model.order_id
                    vc.positionId = model.position_id
                    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.newWorkBlock = {[weak self] in
                    guard let self = self else { return }
                    if self.viewModel.positionList.count == 10 {
                        YHHUD.flash(message: "新增职位不能超过10条")
                    } else {
                        let vc = YHWorkExperiencePositionViewViewController()
                        vc.workID = workId
                        vc.orderID = orderID
                        self.navigationController?.pushViewController(vc, animated: true)
                    }
                    
                }
                cell.backgroundColor = .clear
                cell.contentView.backgroundColor = .clear
                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 {
            let count = fileDataSource?.count ?? 0
            return CGFloat(69 * count + 171)
        } else {
            if indexPath.row == 0 {
                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
                    h = h + 52
                    if isShow && message.count == 0 {
                        h = h + 20
                    }
                }
                return CGFloat(h + 52 + 14 + 386)
            } else {
                var height = 23 + 154
                for item in viewModel.positionList {
                    if item.position_name == "" {
                        height = height + 52
                    } else {
                        let text = item.position_name // 要显示的文本内容
                        let font = UIFont.PFSC_B(ofSize: 14) // 字体大小
                        let maxWidth = 143.0 // 最大宽度限制
                        
                        // 创建NSAttributedString对象并设置属性
                        let attributes = [NSAttributedString.Key.font : font] as [NSAttributedString.Key : Any]
                        _ = NSMutableAttributedString(string: text, attributes: attributes)
                         
                        // 根据指定的最大宽度和字体大小计算文本的高度
                        let size = (text as NSString).boundingRect(with: CGSize(width: maxWidth, height: .greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil).size
                        if size.height > 20 {
                            height = height + 72
                        } else {
                            height = height + 52
                        }
                    }
                    if isShowPrompt && item.missing_item_num != 0 {
                        height = height + 20
                    }
                }
                return CGFloat(height)
            }
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 7
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

extension YHWorkExperienceViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if isKeyboardShow {
            if stepView.currentIndex != 0 {
                self.view.endEditing(true)
            }
        }
    }
}
