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

import UIKit
import AttributedString

class YHGCWorkExperienceViewController: YHBaseViewController {
    var bottomView: YHBottomNextView!
    var tableView: UITableView!
    var viewModel: YHGCWorkExperienceViewModel!
    var baseDataSource: [YHSectionWorkExperienceModel]?
    var introductionDataSource: [YHWorkExperienceProjectModel]?
    var fileDataSource: [YHWorkExperienceFileModel]?
    var workID: Int = 0
    var orderID: Int = 0
    var isMore: Bool = false
    var isShowPrompt: Bool = false
    var isShowMessageSelect: Bool = true
    var isKeyboardShow: Bool = false
    var selectReasonIndex: Int = 5
    var selectEditItem = YHWorkExperienceFileModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHGCWorkExperienceViewModel()
        gk_navTitle = "工作经验信息填写"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        
        setView()
        getData()
    }
    
    func getData() {
        viewModel.requestWorkPositionDetail(workID, orderID) {[weak self] success, _ in
            guard let self = self else { return }
            if success ?? false {
                updateDataSource()
            } else {
                self.viewModel.position.order_id = orderID
                updateDataSource()
            }
        }
    }
    
    func updateDataSource() {
        bottomView.nextButton.setTitle("提交", for: .normal)
        self.baseDataSource = self.viewModel.getBaseDataSource(false)
        self.tableView.reloadData()
    }
    
    func setView() {
        tableView = {
            let tableView = UITableView(frame: .zero, style: .grouped)
            if #available(iOS 11.0, *) {
                tableView.contentInsetAdjustmentBehavior = .never
            }
            tableView.sectionHeaderHeight = 16
            tableView.backgroundColor = .clear
            tableView.separatorStyle = .none
            tableView.delegate = self
            tableView.dataSource = self
            tableView.register(cellWithClass: YHWorkExperiencePositionListTableViewCell.self)
            tableView.register(cellWithClass: YHWorkExperiencePositionReasonTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.bottom.equalTo(view)
        }
        
        bottomView = {
            let bottom = YHBottomNextView()
            bottom.saveButton.isHidden = true
            bottom.nextButton.snp.makeConstraints { make in
                make.right.equalTo(-16)
                make.top.equalTo(10)
                make.height.equalTo(44)
                make.left.equalTo(16)
            }
            bottom.nextblock = { [weak self] in
                bottom.nextButton.isEnabled = false
                guard let self = self else { return }
                if self.viewModel.isCanNext() {
                    self.viewModel.saveWorkPosition(callBackBlock: {[weak self] _, error in
                        guard let self = self else { return }
                        bottom.nextButton.isEnabled = true
                        if let error = error {
                            YHHUD.flash(message: error.errorMsg )
                        } else {
                            YHHUD.hideFlashMessage()
                            YHHUD.flash(message: "提交成功")
                            self.navigationController?.popViewController()
                        }
                    })
                } else {
                    bottom.nextButton.isEnabled = true
                    self.isShowPrompt = true
                    self.updateDataSource()
                    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()
    }
    
}

extension YHGCWorkExperienceViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: YHWorkExperiencePositionListTableViewCell.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 != .id4 && id != .id5 && id != .id8 {
                self.updateDataSource()
            }
        }
        cell.companyBlock = {[weak self] model in
            guard let self = self else { return }
            self.viewModel.updateCompanyModel(model.company_name ?? "")
        }
        return cell
      
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        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
                if data.id == .id6 {
                    h += 72
                } else {
                    h += 52
                }
                if isShow && message.count == 0 {
                    h += 20
                }
            }
            return CGFloat(h + 52 + 14)
        } else {
            return UITableView.automaticDimension
        }
    }
    
    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 16
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}
