//
//  YHFileRenameInputView.swift
//  galaxy
//
//  Created by edy on 2024/3/12.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//
/*
【Usage】
 let view = YHFileRenameInputView.inputView(defalutText:"adfasfsf")
 view.editBlock = {
    text in
 }
 */

import UIKit

class YHFileRenameInputView: UIView {
    
    static let height = 217.0
    var maxWordsCount = 30
    var editBlock: ((String?) -> Void)?
    var dismissBlock: (() -> Void)?
    var confirmBgColor: UIColor = .brandMainColor {
        didSet {
            confirmBtn.backgroundColor = confirmBgColor
        }
    }

    lazy var blackMaskView: UIView = {
        let view = UIView(frame: UIScreen.main.bounds)
        view.backgroundColor = UIColor(hex: 0x0F1214, alpha: 0.5)
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismiss))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        let tap = UITapGestureRecognizer(target: self, action: #selector(didWhiteContentViewTap))
        view.addGestureRecognizer(tap)
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_B(ofSize: 17)
        label.text = "文件重命名"
        return label
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "my_cer_sheet_close"), for: .normal)
        btn.addTarget(self, action: #selector(dismiss), for: .touchUpInside)
        return btn
    }()
    
    lazy var topLine: UIView = {
       let view = UIView()
       view.backgroundColor = .brandGrayColor3
       return view
    }()
    
    lazy var inputContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .contentBkgColor
        view.layer.cornerRadius = kCornerRadius6
        view.clipsToBounds = true
        return view
    }()
    
    lazy var textField: UITextField = {
        let textField = UITextField()
        textField.backgroundColor = .clear
        textField.attributedPlaceholder = NSAttributedString(string: "请输入文件名称", attributes: [NSAttributedString.Key.foregroundColor: UIColor.brandGrayColor5])
        textField.font = UIFont.PFSC_M(ofSize: 16)
        textField.tintColor = UIColor.brandMainColor
        textField.textColor = UIColor.mainTextColor
        textField.delegate = self
        textField.clearButtonMode = .whileEditing
        textField.returnKeyType = .done
        return textField
    }()
    
    lazy var cancelBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("取消", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.backgroundColor = .contentBkgColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickCancelBtn), for: .touchUpInside)
        return btn
    }()
    
    lazy var confirmBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("确定".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickConfirmBtn), for: .touchUpInside)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    static func inputView(defalutText: String?, _  placeholde: String = "请输入文件名称", _ title: String = "文件重命名") -> YHFileRenameInputView {
        let view = YHFileRenameInputView(frame: CGRect(x: 0, y: 0, width: KScreenWidth, height: Self.height))
        view.textField.text = defalutText
        view.textField.attributedPlaceholder = NSAttributedString(string: placeholde, attributes: [NSAttributedString.Key.foregroundColor: UIColor.brandGrayColor5])
        view.titleLabel.text = title
        if placeholde == "请输入10字以内的标签" {
            view.maxWordsCount = 10
        }
        return view
    }
    
    func createUI() {

        self.addSubview(whiteContentView)
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(closeBtn)
        whiteContentView.addSubview(topLine)
        whiteContentView.addSubview(inputContentView)
        inputContentView.addSubview(textField)
        whiteContentView.addSubview(cancelBtn)
        whiteContentView.addSubview(confirmBtn)
        
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = whiteContentView.bounds
        layer.path = path.cgPath
        whiteContentView.layer.mask = layer
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.top.bottom.equalToSuperview()
        }
        titleLabel.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(52.0)
        }
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24.0)
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalTo(titleLabel)
        }
        topLine.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(titleLabel.snp.bottom)
            make.height.equalTo(1)
        }
        inputContentView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.top.equalTo(topLine.snp.bottom).offset(20)
            make.height.equalTo(48)
        }
        textField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(20)
            make.centerY.equalToSuperview()
        }
        cancelBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalTo(whiteContentView.snp.centerX).offset(-6)
            make.top.equalTo(inputContentView.snp.bottom).offset(30)
            make.height.equalTo(45)
        }
        confirmBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.left.equalTo(whiteContentView.snp.centerX).offset(6)
            make.top.equalTo(cancelBtn)
            make.height.equalTo(45)
        }
    }
}

extension YHFileRenameInputView {
    
    @objc func dismiss() {
        self.textField.resignFirstResponder()
        UIApplication.shared.yhKeyWindow()?.endEditing(true)
        self.dismissBlock?()
    }
    
    @objc func didWhiteContentViewTap() {
        self.textField.becomeFirstResponder()
    }
    
    @objc func didClickCancelBtn() {
        dismiss()
    }
    
    @objc func didClickConfirmBtn() {
        if isEmptyString(textField.text) {
            YHHUD.flash(message: "重命名不可为空")
            return
        }
        if let editBlock = editBlock {
            editBlock(textField.text)
        }
        dismiss()
    }
}

extension YHFileRenameInputView: UITextFieldDelegate {
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.isEmpty == true { // 点击删除
            return true
        }
        
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string)
        if newText.count > self.maxWordsCount {
            if maxWordsCount == 30 {
                YHHUD.flash(message: "重命名限制最多\(maxWordsCount)个字符")
            } else {
                YHHUD.flash(message: "自定义标签限制最多\(maxWordsCount)个字符")
            }
            return false
        }
        return true
    }
}
