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

import UIKit

class YHMyInformationItemCell: UITableViewCell {
    typealias ItemBlock = (_ model: YHUserInformationModel) -> ()
    var block: ItemBlock?
    var titleLabel: UILabel!
    var messageTextField: UITextField!
    var nextStepImageView: UIImageView!
    var centerButton: UIButton!
    var dataSource: YHUserInformationModel? {
        didSet {
            updateAllViews()
        }
    }
    
    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
    }

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        selectionStyle = .none
        setUpView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpView() {
        titleLabel = {
            let label = UILabel()
            label.numberOfLines = 0
            return label
        }()
        contentView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.width.equalTo(112)
            make.left.equalTo(21)
        }
        
        messageTextField = {
            let textField = UITextField()
            textField.delegate = self
            textField.textColor = UIColor.mainTextColor
            textField.font = UIFont.PFSC_M(ofSize: 14)
            textField.adjustsFontSizeToFitWidth = true
            //最小字体
            textField.minimumFontSize = 12
            return textField
        }()
        contentView.addSubview(messageTextField)
        messageTextField.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.left.equalTo(129)
        }
        
        nextStepImageView = {
            let imageView = UIImageView()
            imageView.image = UIImage(named: "form_right_arrow")
            return imageView
        }()
        contentView.addSubview(nextStepImageView)
        nextStepImageView.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.centerY.equalToSuperview()
            make.height.width.equalTo(20)
        }
        
        centerButton = {
            let button = UIButton(type: .custom)
            button.addTarget(self, action: #selector(centerClick), for: .touchUpInside)
            return button
        }()
        contentView.addSubview(centerButton)
        centerButton.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.left.equalTo(112)
        }
        
        let lineView = UIView()
        lineView.backgroundColor = UIColor.separatorColor
        contentView.addSubview(lineView)
        lineView.snp.makeConstraints { make in
            make.right.equalTo(-21)
            make.left.equalTo(21)
            make.height.equalTo(0.5)
            make.bottom.equalToSuperview()
        }
    }
    
    func updateAllViews() {
        guard let dataSource = dataSource else { return }
        if dataSource.isNeed ?? false {
            let str = "*" + (dataSource.title ?? "")
            let attributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.PFSC_R(ofSize: 14),
                .foregroundColor: UIColor.mainTextColor
            ]
            let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
            let starRange = NSRange(location: 0, length: 1)
            questionAttrStr.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.failColor, range: starRange)
            titleLabel.attributedText = questionAttrStr
        } else {
            let str = dataSource.title ?? ""
            let attributes: [NSAttributedString.Key: Any] = [
                .font: UIFont.PFSC_R(ofSize: 14),
                .foregroundColor: UIColor.mainTextColor
            ]
            let questionAttrStr = NSMutableAttributedString(string: str, attributes: attributes)
            titleLabel.attributedText = questionAttrStr
        }
        messageTextField.placeholder = dataSource.prompts
        messageTextField.text = dataSource.message
        if dataSource.isUserKeyBoard ?? false {
            nextStepImageView.isHidden = true
            centerButton.isHidden = true
        } else {
            nextStepImageView.isHidden = false
            centerButton.isHidden = false
            messageTextField.snp.remakeConstraints { make in
                make.top.bottom.equalToSuperview()
                make.right.equalTo(-20)
                make.left.equalTo(129)
            }
        }
       
    }
    
    @objc func centerClick() {
        UIViewController.current?.view.endEditing(true) // 收起键盘
        guard let type = dataSource?.type else { return }
        switch type {
        case .normal:
            printLog("不需要跳转")
        case .address:
            let provice = ""
            let addressPicker = YHAddressViewController(selectProvince: provice)
            addressPicker.backLocationStringController = { (address,province,city,area) in
                self.dataSource?.message = address
                self.dataSource?.value = [province, city]
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHUserInformationModel())
                }
            }
            UIViewController.current?.present(addressPicker, animated: true, completion: nil)
        case .time: break
        case .image: break
        case .id:
            YHOtherPickerView.show(type: .professionalSkill, selectTitle: self.dataSource?.message ?? "") { item in
                print(item)
                self.dataSource?.message = item.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHUserInformationModel())
                }
            }
        case .country:
            let vc = YHSelectCountryViewController()
            vc.backLocationStringController = { (country) in
                self.dataSource?.message = country
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHUserInformationModel())
                }
            }
            UIViewController.current?.navigationController?.pushViewController(vc)
        case .sex: break
        case .marry: break
        case .constellation:
            YHOtherPickerView.show(type: .constellation, selectTitle: self.dataSource?.message ?? "") { item in
                print(item)
                self.dataSource?.message = item.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHUserInformationModel())
                }
            }
        case .school:
            let vc = YHCollegeSearchViewController()
            vc.searchCollegeName = self.dataSource?.message
            vc.selectBlock = {[weak self] text in
                guard let self = self else { return }
                self.dataSource?.message = text
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHUserInformationModel())
                }
             }
            UIViewController.current?.navigationController?.pushViewController(vc)
        case .degree:
            YHSheetPickerView.show(type:.educationDegree, selectTitle: self.dataSource?.message) {
                [weak self]  item in
                guard let self = self else { return }
                self.dataSource?.message = item.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHUserInformationModel())
                }
            }
        case .selectAddress:
            YHSheetPickerView.show(type:.educationDegree, selectTitle: self.dataSource?.message) {
                [weak self]  item in
                guard let self = self else { return }
                self.dataSource?.message = item.title
                self.updateAllViews()
                if let block = self.block {
                    block(self.dataSource ?? YHUserInformationModel())
                }
            }
        }
    }

}

extension YHMyInformationItemCell: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.isEmpty == true {
            let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            var data = dataSource ?? YHUserInformationModel()
            data.message = newText
            if let block = block {
                block(data)
            }
            return true
        }
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if  newText.count > 30 {
            return false
        }
        
        var data = dataSource ?? YHUserInformationModel()
        data.message = newText
        if let block = block {
            block(data)
        }
        return true
    }
}

