//
//  PQEditPublicTitleView.swift
//  BFFramework
//
//  Created by ak on 2021/7/22.
//  功能：编辑标题

import Foundation
import BFCommonKit

class PQEditPublicTitleView: UIView {
    
    //点击确认回调
    public var confirmBtnClock: ((_ selectTitle: String?) -> Void)?
    
    //VIEW 隐藏回调事件
    public var viewIsHiddenCallBack: (() -> Void)?

    lazy var backView: UIView = {
        let backView = UIView()
        backView.addCorner(corner: 1.5)
        backView.backgroundColor = .white
        return backView
    }()

    lazy var closeView: UIView = {
        let closeView = UIView()
        closeView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8)
        return closeView
    }()

    // 输入框
    lazy var inputTV: PQTextView = {
        let inputTV = PQTextView()
        inputTV.font = UIFont.systemFont(ofSize: 17, weight: .regular)
        inputTV.backgroundColor = .clear
        inputTV.textColor = .black
        inputTV.maxTextLength = 30
        inputTV.placeHolderDefultPoint = CGPoint(x: 5, y: 0)
        inputTV.tintColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
        inputTV.placeHolder = "我见过你眼中的春与秋，胜过我见过的所有山川河流"
        inputTV.showsVerticalScrollIndicator = false
        inputTV.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        return inputTV
    }()

    // 输入框背景
    lazy var inputBgView: UIView = {
        let inputBgView = UIView()
        inputBgView.backgroundColor = .clear
        inputBgView.addCorner(corner: 10)
        inputBgView.layer.cornerRadius = 7
        inputBgView.layer.borderWidth = 2
        inputBgView.layer.borderColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue).cgColor
        return inputBgView
    }()

    // 确定按钮
    lazy var confirmBtn: UIButton = {
        let confirmBtn = UIButton()
        confirmBtn.backgroundColor = UIColor.hexColor(hexadecimal: PQBFConfig.shared.styleColor.rawValue)
        confirmBtn.setTitle("确定", for: .normal)
        confirmBtn.setTitleColor(.white, for: .normal)
        confirmBtn.setTitleColor(UIColor.white, for: .selected)
        confirmBtn.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        confirmBtn.addCorner(corner: 3)

        confirmBtn.addTarget(self, action: #selector(btnClick(sender:)), for: .touchUpInside)
        return confirmBtn
    }()

    // 标题列表
    lazy var titleCollectionView: UICollectionView = {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        flowLayout.minimumLineSpacing = 0
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.scrollDirection = .vertical
 
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)

        collectionView.showsVerticalScrollIndicator = false
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        collectionView.register(PQEditPublicTitleViewContentCell.self, forCellWithReuseIdentifier: String(describing: PQEditPublicTitleViewContentCell.self))
        if #available(iOS 11.0, *) {
            collectionView.contentInsetAdjustmentBehavior = .never
        }
        // 延迟scrollView上子视图的响应，所以当直接拖动UISlider时，如果此时touch时间在150ms以内，UIScrollView会认为是拖动自己，从而拦截了event，导致UISlider接收不到滑动的event
        collectionView.delaysContentTouches = false
        return collectionView
    }()

    // 标题数据
    var titles: Array<String> = Array() {
        didSet {
            titleCollectionView.reloadData()
        }
        
    }

    override init(frame: CGRect) {
        super.init(frame: frame)

        let ges = UITapGestureRecognizer(target: self, action: #selector(viewClick))
        closeView.addGestureRecognizer(ges)
        backgroundColor = .clear

        addSubview(closeView)
        addSubview(backView)

        backView.addSubview(inputBgView)
        inputBgView.addSubview(inputTV)

        inputBgView.addSubview(confirmBtn)

        backView.addSubview(titleCollectionView)

        backView.snp.makeConstraints { make in
            make.left.width.bottom.equalToSuperview()
            make.height.equalTo(min(640, cScreenHeigth))
//            make.width.equalTo(cScreenWidth)
//            make.height.equalTo(min(640, cScreenHeigth))
//            make.bottom.equalToSuperview()
        }

        closeView.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.width.equalTo(cScreenWidth)
            make.height.equalTo(cScreenHeigth - 640)
            make.top.equalToSuperview()
        }

        inputBgView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(68)
            make.top.equalToSuperview().offset(20)
        }

        inputTV.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(14)
            make.width.equalTo(259)
            make.height.equalTo(48)
            make.top.equalToSuperview().offset(10)
        }

        confirmBtn.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.width.equalTo(58)
            make.height.equalTo(68)
            make.top.equalToSuperview()
        }

        titleCollectionView.snp.makeConstraints { make in
            make.top.equalTo(inputBgView.snp.bottom).offset(10)
            make.width.right.equalToSuperview()
            make.bottom.equalTo(0 - cAKSafeAreaHeight)
//            make.width.equalTo(cScreenWidth)
//            make.height.equalTo(542 - cAKSafeAreaHeight)
        }
 
//        titleCollectionView.reloadData()
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    /// 按钮点击事件
    @objc func btnClick(sender _: UIButton?) {
        BFLog(message: "点击了确定 \(String(describing: inputTV.text))")
   
        if confirmBtnClock != nil {
            confirmBtnClock!(inputTV.text)
            inputTV.text = ""
        }
        viewClick()
    }

    @objc func viewClick() {
        self.isHidden = true
        inputTV.resignFirstResponder()
        if viewIsHiddenCallBack != nil{
            viewIsHiddenCallBack!()
        }
    }
    
    //显示界面
    func show() {
        isHidden = false
        inputTV.becomeFirstResponder()
    }
}

extension PQEditPublicTitleView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UIScrollViewDelegate {
    func collectionView(_: UICollectionView, numberOfItemsInSection _: Int) -> Int {
        return titles.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: PQEditPublicTitleViewContentCell.self), for: indexPath) as! PQEditPublicTitleViewContentCell
        cell.titleStr = titles[indexPath.row]
        return cell
    }

    func collectionView(_: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        BFLog(message: "选择了 \(titles[indexPath.item])")
        inputTV.text = titles[indexPath.item]
    }

    func collectionView(_ collectionView: UICollectionView, layout _: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let title = titles[indexPath.row]
 
        let textSize =  sizeWithText(text: title, font: UIFont.systemFont(ofSize: 17, weight: .regular), size: CGSize.init(width: 295, height: CGFloat.greatestFiniteMagnitude))

        //28  是 cell label 上下边距总和
        return CGSize(width: cScreenWidth, height: textSize.height + 28)
    }

     func scrollViewWillBeginDecelerating(_: UIScrollView) {
        inputTV.resignFirstResponder()
    }
}

class PQEditPublicTitleViewContentCell: UICollectionViewCell {
    lazy var titleLab: UILabel = {
        let titleLab = UILabel()
        titleLab.font = UIFont.systemFont(ofSize: 17, weight: .regular)
        titleLab.textColor = .black
        titleLab.numberOfLines = 0
        titleLab.lineBreakMode = .byCharWrapping
        titleLab.isUserInteractionEnabled = true
        titleLab.textAlignment = .left
        return titleLab
    }()

    // 手势提示
    lazy var iconView: UIImageView = {
        let iconView = UIImageView()
        iconView.backgroundColor = .clear
        iconView.image = UIImage.moduleImage(named: "editTitleTips", moduleName: "BFFramework",isAssets: false)
        return iconView
    }()

    lazy var lineView: UIView = {
        let lineView = UIView()
        lineView.backgroundColor = UIColor.hexColor(hexadecimal: "#EFEFEF")
        return lineView
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(titleLab)
        contentView.addSubview(iconView)
        contentView.addSubview(lineView)
        addLayout()
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var titleStr: String? {
        didSet {
            titleLab.text = titleStr
            
            if(titleLab.text?.count ?? 0 == 0){
                lineView.backgroundColor = .white
                iconView.isHidden = true
            }else{
                lineView.backgroundColor = UIColor.hexColor(hexadecimal: "#EFEFEF")
                iconView.isHidden = false
            }
            addLayout()
        }
    }

    func addLayout() {
        
        let textSize =  sizeWithText(text: titleStr ?? "", font: UIFont.systemFont(ofSize: 17, weight: .regular), size: CGSize.init(width: 295, height: CGFloat.greatestFiniteMagnitude))
  
        titleLab.snp.remakeConstraints { make in
            make.height.equalTo(textSize.height * cAdaptatWidth)
            make.right.equalToSuperview().offset(-64)
            make.left.equalToSuperview().offset(16)
            make.top.equalToSuperview().offset(12)
        }
  
        lineView.snp.makeConstraints { make in
           
            make.right.equalToSuperview().offset(-16)
            make.left.equalToSuperview().offset(16)
            make.bottom.equalToSuperview().offset(-1)
            make.height.equalTo(1)
        }

        iconView.snp.remakeConstraints { make in
            make.width.height.equalTo(24)
            make.right.equalToSuperview().offset(-16)
            make.top.equalTo(contentView.snp.top).offset(14)
        }
    }
}
