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

import UIKit

class YHWorkExperienceListViewController: YHBaseViewController {
    var bottomView: UIView!
    var bottomButton: UIButton!
    var tableView: UITableView!
    var dataSource: [YHWorkItemListModel]?
    var viewModel: YHWorkItemListViewModel?
    var isMore: Bool = false
    var orderId: Int = 0
    var showPrompt: Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = YHWorkItemListViewModel()
        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()
    }
    
    func getData() {
        viewModel?.requestWorkList("\(orderId)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            self.dataSource = success
            self.tableView.reloadData()
        })
    }
    
    func updateDataSource() {
       
        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.register(cellWithClass: YHWorkExperienceListTableViewCell.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 = UIView()
            bottom.backgroundColor = .white
            return bottom
        }()
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(k_Height_safeAreaInsetsBottom() + 64)
        }
        
        bottomButton = {
            let button = UIButton(type: .custom)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("提交", for: .normal)
            button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.clipsToBounds = true
            button.addTarget(self, action: #selector(submit), for: .touchUpInside)
            return button
        }()
        bottomView.addSubview(bottomButton)
        bottomButton.snp.makeConstraints { make in
            make.right.equalTo(-16)
            make.top.equalTo(8)
            make.height.equalTo(48)
            make.left.equalTo(16)
        }
        
        bottomButton.layoutIfNeeded()
        bottomButton.addYinHeGradualLayer()
    }
    
    @objc func submit() {
        guard let dataSource = dataSource else { return }
        for item in dataSource {
            if item.vacant_num ?? 0 > 0 {
                showPrompt = true
                tableView.reloadData()
                YHHUD.flash(message: "您的工作经验未全部填写完成，请先填写完成再提交")
                return
            }
        }
        viewModel?.requestSaveAllWorkExperience("\(orderId)", callBackBlock: {[weak self] success, error in
            guard let self = self else { return }
            if success ?? false {
                self.navigationController?.popViewController(animated: true)
            }
        })
    }
    
    func showDeleteAlert(_ model: YHWorkItemListModel) {
        YHCommonAlertView.show("", "您确定要删除这份工作经验吗？", "取消", "确认") {
            self.viewModel?.requestDeleteWorkExperience("\(model.id ?? 0)", callBackBlock: {[weak self] success, error in
                guard let self = self else { return }
                self.getData()
            })
        }
    }
}

extension YHWorkExperienceListViewController: 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: YHWorkExperienceListTableViewCell.self)
        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 firstModel = self.dataSource?.first
            let vc = YHWorkExperienceViewController()
            vc.workExperienceID = "\(model.id ?? 0)"
            vc.orderID = self.orderId
            vc.isShowMessageSelect = true
            if firstModel?.id == model.id {
                vc.isShowMessageSelect = false
            }
            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 = YHWorkExperienceViewController()
                vc.isShowMessageSelect = true
                vc.orderID = self.orderId
                self.navigationController?.pushViewController(vc, animated: true)
            }
        }
        cell.backgroundColor = .clear
        cell.contentView.backgroundColor = .clear
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let number = dataSource?.count ?? 0
        var height = 23 + 154
        if let data = dataSource {
            for item in data {
                if item.company_name == "" {
                    height = height + 52
                } 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 = height + 96
                    } else {
                        height = height + 76
                    }
                }
            }
        }
        return CGFloat(height)
    }
}

