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

import UIKit
import IQKeyboardManagerSwift

class YHEditInterestViewController: YHBaseViewController {
    var collectionView: UICollectionView!
    var nextButton: UIButton!
    var normalItems: [YHInterestModel] = [YHInterestModel(name: "香港子女教育", isNormal: true, isSelect: false), YHInterestModel(name: "香港房产", isNormal: true, isSelect: false), YHInterestModel(name: "香港创业", isNormal: true, isSelect: false), YHInterestModel(name: "香港就业", isNormal: true, isSelect: false), YHInterestModel(name: "港宝", isNormal: true, isSelect: false), YHInterestModel(name: "香港保险", isNormal: true, isSelect: false), YHInterestModel(name: "香港商务", isNormal: true, isSelect: false), YHInterestModel(name: "ESTP(企业家)", isNormal: true, isSelect: false), YHInterestModel(name: "ENTJ(指挥官)", isNormal: true, isSelect: false), YHInterestModel(name: "ENTP(辩论家)", isNormal: true, isSelect: false), YHInterestModel(name: "INTJ(建筑师)", isNormal: true, isSelect: false)]
    var likeItems: [YHInterestModel] = [YHInterestModel(name: "+自定义", isNormal: false, isSelect: true)]
    var viewModel: YHEditViewModel = YHEditViewModel()
    var model: YHUserNameCardInfo = YHUserNameCardInfo()

    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(dismissed))
        view.addGestureRecognizer(tap)
        view.isHidden = true
        return view
    }()
    
    var renameInputView: YHFileRenameInputView = {
        let view = YHFileRenameInputView.inputView(defalutText: "请输入自定义标签", "请输入10字以内的标签", "请输入自定义标签")
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        setView()
        getData()
    }
    
    func getData() {
        viewModel.model = model
        for item in model.draftTopics {
            let model = YHInterestModel(name: item, isNormal: false, isSelect: false)
            self.likeItems.insert(model, at: likeItems.count - 1)
        }
        
        for item in model.topics {
            if let index = normalItems.firstIndex(where: {$0.name == item}) {
                normalItems[index].isSelect = !normalItems[index].isSelect
            }
            if let index = likeItems.firstIndex(where: {$0.name == item}) {
                likeItems[index].isSelect = !likeItems[index].isSelect
            }
        }
        
        collectionView.reloadData()
    }
    
    func setView() {
        gk_navTitle = "兴趣话题"
        addKeyBoardNotify()
        view.backgroundColor = .white
        collectionView = {
            // 创建集合视图布局
            let layout = YHSearchItemLayout()
            layout.scrollDirection = .vertical
            layout.minimumInteritemSpacing = 12
            // 创建集合视图
            let collectView = UICollectionView(frame: .zero, collectionViewLayout: layout)
            collectView.delegate = self
            collectView.dataSource = self
            collectView.backgroundColor = .white
            // 注册自定义单元格
            collectView.register(YHEditInterestViewCell.self, forCellWithReuseIdentifier: YHSearchInfoHistoryCell.cellReuseIdentifier)
            collectView.register(YHEditInterestViewHeaderView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "YHEditInterestViewHeaderView")
            return collectView
        }()
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(21)
            make.right.equalTo(-21)
            make.bottom.equalTo(-8 - k_Height_safeAreaInsetsBottom() - 48)
            make.top.equalTo(k_Height_NavigationtBarAndStatuBar)
        }
        
        nextButton = {
            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.setTitleColor( UIColor(hex: 0xffffff), for: .normal)
            button.layer.cornerRadius = kCornerRadius3
            button.addTarget(self, action: #selector(nextStep), for: .touchUpInside)
            return button
        }()
        view.addSubview(nextButton)
        nextButton.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-8 - k_Height_safeAreaInsetsBottom())
            make.height.equalTo(48)
        }
        
        view.addSubview(blackMaskView)
        view.addSubview(renameInputView)
        renameInputView.snp.makeConstraints { make in
            make.left.right.equalTo(view)
            make.height.equalTo(YHEmailInputAlertView.height)
            make.bottom.equalToSuperview().offset(YHEmailInputAlertView.height)
        }
        
        renameInputView.editBlock = {
            [weak self] text in
            guard let self = self else { return }
            
            if let text = text {
                if let _ = normalItems.firstIndex(where: {$0.name == text}) {
                    YHHUD.flash(message: "请不要添加重复的标签噢")
                    return
                }
                if let _ = likeItems.firstIndex(where: {$0.name == text}) {
                    YHHUD.flash(message: "请不要添加重复的标签噢")
                    return
                }
                self.viewModel.didChange = true
                let model = YHInterestModel(name: text, isNormal: false, isSelect: false)
                self.likeItems.insert(model, at: 0)
                self.collectionView.reloadData()
            }
        }
    }
    
    @objc func dismissed() {
        renameInputView.textField.resignFirstResponder()
    }
    
    @objc func nextStep() {
        var topics: [String] = []
        var draftTopics: [String] = []
        for item in normalItems {
            if item.isSelect {
                topics.append(item.name)
            }
        }
        for like in likeItems {
            if like.isSelect && like.name != "+自定义" {
                topics.append(like.name)
            }
            
            if like.name != "+自定义" {
                draftTopics.append(like.name)
            }
        }
        viewModel.requestSaveTopics(topics: topics, draft_topics: draftTopics) {[weak self] success, _ in
            guard let self = self else { return }
            if success {
                self.navigationController?.popViewController(animated: true)
            } else {
                YHHUD.flash(message: "保存失败")
            }
        }
    }
    
    // 计算文字宽度大小
    func getwith(font: UIFont, height: CGFloat, string: String) -> CGSize {
        let size = CGSize.init(width: CGFloat(MAXFLOAT), height: height)
        let dic = [NSAttributedString.Key.font: font] // swift 4.2
        var strSize = string.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return CGSize(width: ceil(strSize.width), height: strSize.height)
    }
    
    override func backItemClick(_ sender: Any) {
        if viewModel.didChange {
            view.resignAllFirstResponders()
            YHCommonAlertView.show("", "您尚未保存修改，确定关闭吗？", "仍然关闭", "继续编辑", fullGuestureEnable: false) {
                self.navigationController?.popViewController()
            } callBack: {
            }
        } else {
            self.navigationController?.popViewController()
        }
    }
    
    /// 是否可以返回，包括点击返回和手势返回，默认YES
    override func navigationShouldPop() -> Bool {
        if viewModel.didChange {
            view.resignAllFirstResponders()
            YHCommonAlertView.show("", "您尚未保存修改，确定关闭吗？", "仍然关闭", "继续编辑", fullGuestureEnable: false) {
                self.navigationController?.popViewController()
            } callBack: {
            }
            return false
        }
        return true
    }
}

extension YHEditInterestViewController {
    
    func addKeyBoardNotify() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardNotification(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    func removeNotify() {
        NotificationCenter.default.removeObserver(self)
    }
    
    @objc func handleKeyboardNotification(_ notification: Notification) {
        
        if notification.userInfo != nil {
            
            guard let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue else { return }
            
            let isKeyboardShow = notification.name == UIResponder.keyboardWillShowNotification
            self.blackMaskView.isHidden = !isKeyboardShow
            let bottomMargin = (isKeyboardShow ? -keyboardFrame.height : keyboardFrame.height)
            
            if !isKeyboardShow {
                IQKeyboardManager.shared.isEnabled = true
            }
            
            self.renameInputView.snp.updateConstraints { make in
                make.bottom.equalToSuperview().offset(bottomMargin)
            }
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
        }
    }
}

extension YHEditInterestViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
        // 返回单元格数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return normalItems.count
        } else {
            if likeItems.count > 20 {
                return 20
            }
            return likeItems.count
        }
    }
    
    // 返回每个单元格的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var model = YHInterestModel(name: "", isNormal: false, isSelect: false)
        if indexPath.section == 0 {
            model = normalItems[indexPath.item]
        } else {
            model = likeItems[indexPath.item]
        }
        let size = self.getwith(font: UIFont.systemFont(ofSize: 12), height: 24, string: model.name)
        var width = size.width + 12*2.0
        if !model.isNormal && !model.isSelect {
            width += 22
        }
        if width > 226.0 {
            width = 226.0
        }
        return CGSize(width: width, height: 30)
    }
    
    // 返回自定义单元格
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHSearchInfoHistoryCell.cellReuseIdentifier, for: indexPath) as? YHEditInterestViewCell else { return UICollectionViewCell() }
        if indexPath.section == 0 {
            cell.dataSource = normalItems[indexPath.item]
        } else {
            cell.dataSource = likeItems[indexPath.item]
        }
        cell.deleteBlock = { [weak self] in
            guard let self = self else { return }
            self.likeItems.remove(at: indexPath.item)
            self.collectionView.reloadData()
            self.viewModel.didChange = true
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            normalItems[indexPath.item].isSelect = !normalItems[indexPath.item].isSelect
        } else {
            if indexPath.row != likeItems.count - 1 {
                likeItems[indexPath.item].isSelect = !likeItems[indexPath.item].isSelect
            } else {
                // 添加标签
                renameInputView.textField.text = ""
                renameInputView.textField.becomeFirstResponder()
            }
        }
        collectionView.reloadData()
        viewModel.didChange = true
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
            return CGSize(width: collectionView.frame.width, height: 50) // 设置section view的高度
    }
    
    // 创建section view
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionView.elementKindSectionHeader {
            guard let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "YHEditInterestViewHeaderView", for: indexPath) as? YHEditInterestViewHeaderView else { return UICollectionReusableView() }

            if indexPath.section == 0 {
                headerView.label.text = "话题标签"
            }
            if indexPath.section == 1 {
                headerView.label.text = "自定义标签"
            }
            return headerView
        }
        return UICollectionReusableView()
    }
}

class YHEditInterestViewHeaderView: UICollectionReusableView {
    var label = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupLabel()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupLabel() {
        label.frame = self.bounds
        label.textAlignment = .left
        label.textColor = UIColor.mainTextColor
        label.font = UIFont.PFSC_M(ofSize: 15)
        addSubview(label)
    }
}

class YHEditInterestViewCell: UICollectionViewCell {
    typealias DeleteBlock = () -> Void
    var deleteBlock: DeleteBlock?
    static let cellReuseIdentifier = "YHEditInterestViewCell"
    
    var dataSource: YHInterestModel? {
        didSet {
            updateData()
        }
    }
    
    lazy var titleLabel: UILabel =  {
        var label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textAlignment = .left
        label.textColor = UIColor.mainTextColor
        return label
    }()

    lazy var deleteButton: UIButton =  {
        var button = UIButton()
        button.setImage(UIImage(named: "set_interest_delete"), for: .normal)
        button.addTarget(self, action: #selector(deleteClick), for: .touchUpInside)
        return button
    }()

    lazy var addImageView: UIImageView =  {
        var label = UIImageView()
        label.image = UIImage(named: "")
        return label
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    private func setupUI() {
        
        contentView.backgroundColor = UIColor(hexString: "#F4F6FA")
        contentView.clipsToBounds = true
        contentView.addSubview(titleLabel)
        contentView.addSubview(deleteButton)

        titleLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(12.0)
            make.right.equalToSuperview().offset(-12.0)
        }
        
        deleteButton.snp.makeConstraints { make in
            make.right.top.bottom.equalToSuperview()
            make.width.equalTo(22.0)
        }
    }
    
    @objc func deleteClick() {
        if let block = deleteBlock {
            block()
        }
    }
    
    func updateData() {
        guard let dataSource = dataSource else {
            return
        }
        contentView.layer.masksToBounds = true
        contentView.layer.cornerRadius = kCornerRadius3
        titleLabel.text = dataSource.name
        if dataSource.isNormal {
            deleteButton.isHidden = true
            if dataSource.isSelect {
                contentView.layer.borderWidth = 1
                contentView.layer.borderColor = UIColor.brandMainColor.cgColor
                titleLabel.textColor = UIColor.brandMainColor
            } else {
                contentView.layer.borderWidth = 0
                contentView.layer.borderColor = UIColor.brandMainColor.cgColor
                titleLabel.textColor = UIColor.mainTextColor
            }
        } else {
            if dataSource.isSelect {
                contentView.layer.borderWidth = 1
                contentView.layer.borderColor = UIColor.brandMainColor.cgColor
                titleLabel.textColor = UIColor.brandMainColor
                deleteButton.isHidden = true
            } else {
                contentView.layer.borderWidth = 0
                contentView.layer.borderColor = UIColor.brandMainColor.cgColor
                titleLabel.textColor = UIColor.mainTextColor
                deleteButton.isHidden = false
            }
        }
    }
}
