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

import UIKit

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
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHWorkExperienceViewModel()
        gk_navTitle = "工作经验信息填写"
        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)
        // Do any additional setup after loading the view.
    }
    
    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)
        }
        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:.plain)
            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
                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 }
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            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 {
                    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)
        }
    }
    
    @objc func keyboardWillShow(_ notification: Notification) {
        // 当键盘将要显示时调用此函数
        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) {
        // 当键盘将要隐藏时调用此函数
        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)
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

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 {
            if self.viewModel.mainModel.is_project_introduction == 1 {
                return 1
            } else {
                if viewModel.mainModel.not_need_upload_file == 1 {
                    return 1
                }
                return 2
            }
        }
        if stepView.currentIndex == 4 {
            if viewModel.mainModel.not_need_upload_file == 1 {
                return 1
            }
            return 2
        }
        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: 300, height: 300), 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.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: 300, height: 300), 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.viewModel?.requestDeleteWorkExperienceProject("\(model.id ?? 0)", callBackBlock: {[weak self] success, error in
                        guard let self = self else { return }
                        self.getData()
                    })
                }
                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 {
                if indexPath.row == 0 {
                    let cell = tableView.dequeueReusableCell(withClass: YHWorkMessageSelectTableViewCell.self)
                    cell.dataSource = viewModel.mainModel.not_need_upload_file
                    cell.isNeedFileBlock = { [weak self] value in
                        guard let self = self else { return }
                        self.viewModel.updateNotNeedUploadFile(value: value)
                        self.tableView.reloadData()
                    }
                    cell.isHidden = !self.isShowMessageSelect
                    return cell
                } else {
                    let cell = tableView.dequeueReusableCell(withClass: YHWorkFileSyncTableViewCell.self)
                    cell.dataSource = fileDataSource
                    cell.addIntroductionBlock = { [weak self] in
                        guard let self = self else { return }
                        YHImagePickerView.show() {[weak self] image in
                            guard let self = self else { return }
                            YHHUD.show(.progress(message: ""))
                            self.viewModel.uploadImage(image) {[weak self] success, error in
                                guard let self = self else { return }
                                guard let url = success else { return }
                                let timestamp = Date().timeIntervalSince1970
                                let model = YHWorkExperienceFileModel()
                                model.fileUrl = success ?? ""
                                model.fileName = "\(UInt64(timestamp))" + ".jpg"
                                self.fileDataSource?.append(model)
                                self.viewModel.mainModel.file = self.fileDataSource ?? []
                                self.tableView.reloadData()
                                YHHUD.hide()
                            }
                        }
                    }
                    cell.experienceListBlock = {[weak self] model, type in
                        guard let self = self else { return }
                        if type == .delete {
                            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
                                }
                            }
                        }
                    }
                    return cell
                }
            }
        } else if stepView.currentIndex == 4 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withClass: YHWorkMessageSelectTableViewCell.self)
                cell.dataSource = viewModel.mainModel.not_need_upload_file
                cell.isNeedFileBlock = { [weak self] value in
                    guard let self = self else { return }
                    self.viewModel.updateNotNeedUploadFile(value: value)
                    self.tableView.reloadData()
                }
                cell.isHidden = !self.isShowMessageSelect
                return cell
            } else {
                let cell = tableView.dequeueReusableCell(withClass: YHWorkFileSyncTableViewCell.self)
                cell.dataSource = fileDataSource
                cell.addIntroductionBlock = { [weak self] in
                    guard let self = self else { return }
                    YHImagePickerView.show() {[weak self] image in
                        guard let self = self else { return }
                        YHHUD.show(.progress(message: ""))
                        self.viewModel.uploadImage(image) {[weak self] success, error in
                            guard let self = self else { return }
                            guard let url = success else { return }
                            let timestamp = Date().timeIntervalSince1970
                            let model = YHWorkExperienceFileModel()
                            model.fileUrl = success ?? ""
                            model.fileName = "\(UInt64(timestamp))" + ".jpg"
                            self.fileDataSource?.append(model)
                            self.viewModel.mainModel.file = self.fileDataSource ?? []
                            self.tableView.reloadData()
                            YHHUD.hide()
                        }
                    }
                }
                cell.experienceListBlock = {[weak self] model, type in
                    guard let self = self else { return }
                    if type == .delete {
                        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
                            }
                        }
                    } else {
                        let vc = YHImageViewController()
                        vc.imgString = model.fileUrl
                        UIViewController.current?.navigationController?.pushViewController(vc)
                    }
                }
                return cell
            }
        } else {
            let cell = tableView.dequeueReusableCell(withClass: YHWorkExperienceTableViewCell.self)
            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 != .id17 && id != .id17 && id != .id18 {
                    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 + 161)
            } else {
                if indexPath.row == 0 {
                    if self.isShowMessageSelect {
                        return 166
                    } else {
                        return 0
                    }
                } else {
                    let count = fileDataSource?.count ?? 0
                    return CGFloat(52 * count + 145)
                }
            }
        } else if stepView.currentIndex == 4 {
            if indexPath.row == 0 {
                if self.isShowMessageSelect {
                    return 166
                } else {
                    return 0
                }
            } else {
                let count = fileDataSource?.count ?? 0
                return CGFloat(52 * count + 145)
            }
        } 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)
        }
    }
}
