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

import UIKit

class YHTopicItemCell: UICollectionViewCell {
    
    static let cellReuseIdentifier = "YHTopicItemCell"
    lazy var titleLabel: UILabel =  {
        var label = UILabel()
        label.font = .PFSC_R(ofSize: 12)
        label.textAlignment = .left
        label.textColor = UIColor.mainTextColor70
        return label
    }()

    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    func setupUI() {
        
        contentView.layer.cornerRadius = 3.0
        contentView.backgroundColor = UIColor.init(hex: 0xF4F6FA)
        contentView.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.top.bottom.equalToSuperview()
            make.left.equalToSuperview().offset(4.0)
            make.right.equalToSuperview().offset(-4.0)
        }
    }
}

class YHMyInterestTopicCell: UITableViewCell {
    typealias EditBlock = () -> Void
    var editBlock: EditBlock?
    static let cellReuseIdentifier = "YHMyInterestTopicCell"
    var topicArr: [String] = []
    var userModel: YHUserNameCardInfo = YHUserNameCardInfo() {
        didSet {
            
            self.editBtn.isHidden = !self.userModel.isCurrentUser

            var isShowList = true
            if self.userModel.isCurrentUser {
                if self.userModel.topics.count <= 0 {
                    isShowList = false
                }
            }
            self.collectionView.isHidden = !isShowList
            self.detailLabel.isHidden = isShowList
            
            self.topicArr.removeAll()
            if self.userModel.topics.count > 0 {
                self.topicArr.append(contentsOf: self.userModel.topics)
            }
            self.layout.dataSource = self.topicArr
            self.layout.invalidateLayout()
            self.collectionView.reloadData()

            let height = self.layout.collectionViewContentSize.height
            printLog("ABC: \(height)")
            
            if isShowList {
                
                self.collectionView.snp.remakeConstraints { make in
                    make.height.equalTo(height)
                    make.left.equalTo(20)
                    make.right.equalTo(-20)
                    make.bottom.equalTo(-24)
                    make.top.equalTo(self.titleLabel.snp.bottom).offset(16)
                }
                self.detailLabel.snp.remakeConstraints { make in
                    make.left.equalTo(20)
                    make.right.equalTo(-20)
                    make.top.equalTo(titleLabel.snp.bottom).offset(16)
                }
                self.setNeedsLayout()
                self.layoutIfNeeded()
                
            } else {
                
                self.detailLabel.snp.remakeConstraints { make in
                    make.left.equalTo(20)
                    make.right.equalTo(-20)
                    make.bottom.equalTo(-24)
                    make.top.equalTo(titleLabel.snp.bottom).offset(16)
                }
                self.collectionView.snp.remakeConstraints { make in
                    make.height.equalTo(height)
                    make.left.equalTo(20)
                    make.right.equalTo(-20)
                    make.top.equalTo(self.titleLabel.snp.bottom).offset(16)
                }
            }
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }

    lazy var cardView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 6.0
        view.clipsToBounds = true
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.text = "兴趣话题"
        label.textColor = UIColor(hexString: "#222222")
        label.textAlignment = .left
        label.font = UIFont.PFSC_M(ofSize: 17)
        return label
    }()
    
    lazy var editBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "people_card_edit"), for: .normal)
        btn.addTarget(self, action: #selector(edit), for: .touchUpInside)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    lazy var layout: YHInterestTopicLayout = {
        let layout = YHInterestTopicLayout()
        layout.scrollDirection = .vertical
        layout.dataSource = self.topicArr
        layout.layoutDelegate = self
        layout.collectionViewWidth = KScreenWidth-20.0*2
        return layout
    }()
    
    lazy var collectionView: YHTagCollectionView = {
        let collectView = YHTagCollectionView(frame: .zero, collectionViewLayout: self.layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .white
        collectView.register(YHTopicItemCell.self, forCellWithReuseIdentifier: YHTopicItemCell.cellReuseIdentifier)
        return collectView
    }()
    
    lazy var detailLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor30
        label.textAlignment = .left
        label.font = UIFont.PFSC_R(ofSize: 14)
        label.numberOfLines = 0
        label.text = "填写你的兴趣爱好，与志同道合的人畅聊共同话题，如MBTI人格测试、艺术、运动、技术等方面。"
        return label
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    func setupUI() {
        
        self.selectionStyle = .none
        self.backgroundColor = .clear
        self.contentView.backgroundColor = .clear
        
        self.contentView.addSubview(self.cardView)
        cardView.addSubview(self.titleLabel)
        cardView.addSubview(collectionView)
        cardView.addSubview(detailLabel)
        
        cardView.addSubview(self.editBtn)
        
        cardView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.top.equalTo(24)
            make.height.equalTo(24)
        }
        
        editBtn.snp.makeConstraints { make in
            make.width.height.equalTo(20)
            make.right.equalTo(-20)
            make.centerY.equalTo(titleLabel)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalTo(-24)
            make.height.equalTo(24)
            make.top.equalTo(titleLabel.snp.bottom).offset(16)
        }
        
        detailLabel.snp.makeConstraints { make in
            make.edges.equalTo(self.collectionView)
        }
    }
    
    @objc func edit() {
        if let block = editBlock {
            block()
        }
    }
}

extension YHMyInterestTopicCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
        // 返回单元格数量
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            
            return topicArr.count
        }
        
        // 返回每个单元格的大小
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            
            let size = self.getwith(font: UIFont.systemFont(ofSize: 12), height: 24, string: topicArr[indexPath.item])
            var width = size.width + 4*2.0
            if width > 226.0 {
                width = 226.0
            }
            return CGSize(width: width, height: 24.0)
        }
        
        // 返回自定义单元格
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHTopicItemCell.cellReuseIdentifier, for: indexPath) as? YHTopicItemCell else {
                return UICollectionViewCell()
            }
            if 0 <= indexPath.item && indexPath.item < topicArr.count {
                cell.titleLabel.text = topicArr[indexPath.item]
            }
            return cell
        }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if 0 <= indexPath.item && indexPath.item < topicArr.count {
//            let text = topicArr[indexPath.item]
        }
    }
    
    // 计算文字宽度大小
    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
        let strSize = string.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return CGSize(width: ceil(strSize.width), height: strSize.height)
    }
}
