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

import UIKit

class YHGCWorkExperienceListViewController: YHBaseViewController {
    var bottomView: YHBottomNextView!
    var tableView: UITableView!
    var dataSource: [YHWorkItemListModel]?
    var viewModel: YHGCWorkItemListViewModel!
    var isMore: Bool = false
    var orderId: Int = 0
    var showPrompt: Bool = false
    var baseData: YHSectionWorkExperienceModel = YHSectionWorkExperienceModel()
    var docData: YHSectionWorkExperienceModel = YHSectionWorkExperienceModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHGCWorkItemListViewModel()
        gk_navTitle = "工作经验信息填写"
        gk_navBackgroundColor = .white
        gk_navBarAlpha = 1.0
        
        setView()
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getData()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        viewModel?.requestWorkTimeRemarkWorkExperience(false, "\(orderId)", 1, callBackBlock: {[weak self] _, _ in
            guard let self = self else { return }
        })
    }
    
    func getData() {
        viewModel?.requestWorkList("\(orderId)", callBackBlock: {[weak self] success, _ in
            guard let self = self else { return }
            self.dataSource = success
            self.baseData = viewModel.getBaseDataSource(showPrompt)
            self.docData = viewModel.getDocDataSource(showPrompt)
            self.tableView.reloadData()
        })
    }
    
    func updateDataSource() {
        self.baseData = viewModel.getBaseDataSource(showPrompt)
        self.docData = viewModel.getDocDataSource(showPrompt)
        self.tableView.reloadData()
    }
    
    func setView() {
        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.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
            tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: 7))
            tableView.register(cellWithClass: YHGCWorkExperienceListTableViewCell.self)
            tableView.register(cellWithClass: YHGCWorkListHasWorkExperienceTableViewCell.self)
            tableView.register(cellWithClass: YHGCWorkListHasDocTableViewCell.self)
            tableView.register(cellWithClass: YHGCWorkExperienceListReasonTableViewCell.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.nextButton.setTitle("提交", for: .normal)
            bottom.nextblock = { [weak self] in
                guard let self = self else { return }
                guard let dataSource = dataSource else { return }
                for item in dataSource {
                    if item.vacant_num ?? 0 > 0 {
                        showPrompt = true
                        tableView.reloadData()
                        YHHUD.flash(message: "您的工作经验未全部填写完成，请先填写完成再提交")
                        return
                    }
                }
                if self.viewModel?.mainModel.has_work_time_overlap == 1 && self.viewModel?.mainModel.why_work_time_overlap.count == 0 {
                    YHHUD.flash(message: "您的工作经验未全部填写完成，请先填写完成再提交")
                    return
                }
                viewModel?.requestWorkTimeRemarkWorkExperience(true, "\(orderId)", 1, callBackBlock: {[weak self] success, _ in
                    guard let self = self else { return }
                    if success ?? false {
                        self.navigationController?.popViewController(animated: true)
                    }
                })
            }
            bottom.saveBlock = { [weak self] in
                guard let self = self else { return }
                viewModel?.requestWorkTimeRemarkWorkExperience(false, "\(orderId)", 1, callBackBlock: {[weak self] _, _ in
                    guard let self = self else { return }
                })
            }
            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()
    }
    
    func showDeleteAlert(_ model: YHWorkItemListModel) {
        YHCommonAlertView.show("", "您确定要删除这份工作经验吗？", "取消", "确认") {
            self.viewModel?.requestDeleteWorkExperience(model.id ?? 0, "\(self.orderId)", callBackBlock: {[weak self] _, _ in
                guard let self = self else { return }
                self.getData()
            })
        }
    }
}

extension YHGCWorkExperienceListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withClass: YHGCWorkListHasWorkExperienceTableViewCell.self)
            cell.dataSource = baseData
            cell.workExperienceBlock = {[weak self] model in
                guard let self = self else { return }
                self.viewModel.updateModel(model)
                self.updateDataSource()
            }
            return cell
        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withClass: YHGCWorkExperienceListTableViewCell.self)
            if self.viewModel.mainModel.has_work_experience == 1 {
                cell.isHidden = false
            } else {
                cell.isHidden = true
            }
            cell.showPrompt = showPrompt
            cell.dataSource = dataSource
            if isMore {
                cell.more()
            } else {
                cell.cannal()
            }
            cell.clickBlock = {[weak self] model in
                guard let self = self else { return }
                let vc = YHGCWorkExperienceViewController()
                vc.workID = model.id ?? 0
                vc.orderID = self.orderId
                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.dataSource?.count == 10 {
                    YHHUD.flash(message: "新增工作经历不能超过10条")
                } else {
                    let vc = YHGCWorkExperienceViewController()
                    vc.orderID = self.orderId
                    vc.workID = 0
                    self.navigationController?.pushViewController(vc, animated: true)
                }
            }
            cell.backgroundColor = .clear
            cell.contentView.backgroundColor = .clear
            return cell
        } else if indexPath.row == 2 {
            let cell = tableView.dequeueReusableCell(withClass: YHGCWorkExperienceListReasonTableViewCell.self)
            if viewModel.mainModel.has_work_time_overlap == 1 && self.viewModel.mainModel.has_work_experience == 1 {             cell.isHidden = false
            } else {
                cell.isHidden = true
            }
            cell.model = viewModel?.mainModel
            cell.clickBlock = { [weak self] value in
                guard let self = self else { return }
                self.viewModel?.mainModel.why_work_time_overlap = value
            }
            return cell
        } else if indexPath.row == 3 {
            let cell = tableView.dequeueReusableCell(withClass: YHGCWorkListHasDocTableViewCell.self)
            if self.viewModel.mainModel.is_consent_required == 1 {
                cell.isHidden = false
            } else {
                cell.isHidden = true
            }
            cell.companyList = self.viewModel.mainModel.list ?? []
            cell.url = self.viewModel.mainModel.consent_template_url
            cell.dataSource = docData
            cell.workExperienceBlock = {[weak self] model in
                guard let self = self else { return }
                self.viewModel.updateModel(model)
                self.updateDataSource()
            }
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            let array = baseData.models ?? []
            var h = 0
            for i in 0..<array.count {
                let data = array[i]
                let message = data.message ?? ""
                let isShow = data.isShowPrompts ?? false
                h += 62
                if isShow && message.count == 0 {
                    h += 20
                }
            }
            return CGFloat(h + 52 + 14)
        }
        
        if indexPath.row == 2 {
            
            if viewModel.mainModel.has_work_time_overlap == 1 && self.viewModel.mainModel.has_work_experience == 1 {
                return UITableView.automaticDimension
            } else {
                return 0
            }
        }
        
        if indexPath.row == 3 {
            if self.viewModel.mainModel.is_consent_required == 1 {
                let array = docData.models ?? []
                var h = 0
                for i in 0..<array.count {
                    let data = array[i]
                    let message = data.message ?? ""
                    let isShow = data.isShowPrompts ?? false
                    h += 68
                    if isShow && message.count == 0 {
                        h += 20
                    }
                }
                return CGFloat(h + 52 + 96 + 14)
            } else {
                return 0
            }
        }
        
        if self.viewModel.mainModel.has_work_experience == 1 {
            _ = dataSource?.count ?? 0
            var height = 14 + 154
            if let data = dataSource {
                for item in data {
                    if item.company_name == "" {
                        height += 76
                    } else {
                        let text = item.company_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 += 96
                        } else {
                            height += 76
                        }
                    }
                    if showPrompt && item.vacant_num != 0 {
                        height += 20
                    }
                }
            }
            return CGFloat(height)
        } else {
            return 0
        }
    }
}
