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

import UIKit

class YHCompanySelectViewController: YHBaseViewController {

    public var backLocationStringController: ((YHCompanyModelListModel) -> Void)?
    var searchView: UITextField!
    var sureButton: UIButton!
    var tableView: UITableView!
    var alertLabel: UILabel!
    var searchDataSource: [YHCompanyModelListModel]?
    var viewModel: YHCompanyViewModel?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        gk_navTitle = "用人单位"
        viewModel = YHCompanyViewModel()
        setView()
        getData()
    }
    
    func getData() {
        tableView.reloadData()
        
    }
    
    func setView() {
        view.backgroundColor = .white
        
        let bgView = {
            let view = UIView()
            view.backgroundColor = UIColor(hex: 0xf8f9fb)
            view.layer.cornerRadius = 3
            return view
        }()
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 16)
            make.height.equalTo(41)
            make.left.equalTo(16)
            make.right.equalTo(-16)
        }
        
        searchView = {
            let searchBar = UITextField()
            searchBar.placeholder = "请输入用人单位全称"
            searchBar.backgroundColor = UIColor(hex: 0xf8f9fb)
            searchBar.font = UIFont.PFSC_R(ofSize: 14)
            searchBar.keyboardType = .default
            searchBar.delegate = self
            searchBar.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 16, height: 42))
            searchBar.leftViewMode = .always
            searchBar.clearButtonMode = .always
            searchBar.layer.cornerRadius = 3
            return searchBar
        }()
        view.addSubview(searchView)
        searchView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 16)
            make.height.equalTo(41)
            make.left.equalTo(16)
            make.right.equalTo(-90)
        }
        
        sureButton = {
            let button = UIButton(type: .custom)
            button.backgroundColor =  UIColor.brandMainColor
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
            button.contentHorizontalAlignment = .center
            button.setTitle("确认", for: .normal)
            button.titleLabel?.font = UIFont.PFSC_M(ofSize: 12)
            button.setTitleColor( UIColor(hex:0xffffff), for: .normal)
            button.addTarget(self, action: #selector(submit), for: .touchUpInside)
            return button
        }()
        view.addSubview(sureButton)
        sureButton.snp.makeConstraints { make in
            make.centerY.equalTo(searchView.snp.centerY)
            make.height.equalTo(33)
            make.width.equalTo(66)
            make.right.equalTo(-20)
        }
        sureButton.addYinHeGradualLayer()
        
        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: YHCompanyTableViewCell.self)
            return tableView
        }()
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar + 78)
            make.bottom.equalTo(-k_Height_safeAreaInsetsBottom() - 64)
            make.left.right.equalTo(view)
        }
        
        alertLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 12)
            label.textColor = UIColor(hex: 0x949494)
            label.numberOfLines = 0
            label.text = "暂未检索到相关企业，请准确、完整输入您的企业名称"
            label.textAlignment = .center
            label.isHidden = true
            return label
        }()
        view.addSubview(alertLabel)
        alertLabel.snp.makeConstraints { make in
            make.left.equalTo(21)
            make.right.equalTo(-21)
            make.height.equalTo(17)
            make.top.equalTo(searchView.snp.bottom).offset(21)
        }
    }
    
    @objc func submit() {
        if let backLocationStringController = backLocationStringController {
            let model = YHCompanyModelListModel()
            model.company_name = searchView.text
            backLocationStringController(model)
            self.navigationController?.popViewController()
        }
    }
}

extension YHCompanySelectViewController: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        if textField.text == "" {
            tableView.isHidden = true
            alertLabel.isHidden = true
        } else {
            viewModel?.requestCompany(textField.text ?? "") { [weak self] success, error in
                guard let self = self else { return }
                if success?.count == 0 {
                    self.alertLabel.isHidden = false
                    self.tableView.isHidden = true
                } else {
                    self.searchDataSource = success
                    self.alertLabel.isHidden = true
                    self.tableView.isHidden = false
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        tableView.isHidden = true
        alertLabel.isHidden = true
        searchDataSource = []
        textField.text = ""
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.count > 0 {
            let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            if newText.count > 100 {
                return false
            }
        }
        return true
    }
}

extension YHCompanySelectViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return searchDataSource?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: YHCompanyTableViewCell.self)
        guard let model = searchDataSource, model.count > indexPath.row else { return cell }
        let newString = model[indexPath.row].company_name?.highlighted(keyWords: searchView.text, highlightColor: UIColor.brandMainColor)
        cell.titleLabel.attributedText = newString
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let text = searchDataSource?[indexPath.row] else { return }
        if let backLocationStringController = backLocationStringController {
            backLocationStringController(text)
            self.navigationController?.popViewController()
        }
    }
}

class YHCompanyTableViewCell: UITableViewCell {
    var titleLabel: UILabel!
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setupUI()
    }
    
    func setupUI() {
        titleLabel = {
            let label = UILabel()
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.textColor = UIColor.mainTextColor
            label.numberOfLines = 0
            return label
        }()
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalTo(21)
            make.right.equalTo(-21)
        }
    }
}

