//
//  YHServiceSelectAlertView.swift
//  galaxy
//
//  Created by edy on 2024/8/19.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import AttributedString
import SmartCodable

class YHServiceItem: SmartCodable {
    var id: Int = 0
    var name: String = ""
    var isSelect: Bool = false
    
    required init() {
        
    }
    
    init(id: Int = 0, name: String = "") {
        self.id = id
        self.name = name
    }
}

class YHServiceSelectAlertView: UICollectionViewCell {
    
    var items: [YHServiceItem] = [] {
        didSet {
            var rowCount = items.count/3
            if items.count%3 != 0 {
                rowCount += 1
            }
            var height = 0.0
            if rowCount > 0 {
                height = 42.0 * Double(rowCount) + 16.0 *  Double(rowCount-1)
            }
            
            collectionView.reloadData()
            collectionView.snp.updateConstraints { make in
                make.height.equalTo(height)
            }
        }
    }
    var confirmBlock: (([Int]) -> Void)?
    
    // 底层蒙版
    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = .alertMaskColor
        return view
    }()
    
    lazy var whiteContentView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = kCornerRadius6
        return view
    }()
    
    lazy var bgImgView: UIView = {
        let view = UIImageView(image: UIImage(named: "service_list_bg"))
        return view
    }()
    
    lazy var iconImgView: UIView = {
        let view = UIImageView(image: UIImage(named: "service_list_icon"))
        return view
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        let a: ASAttributedString = .init("期望银河在您的", .font(UIFont.PFSC_B(ofSize: 18)), .foreground(UIColor.mainTextColor))
        let b: ASAttributedString = .init("香港新生活", .font(UIFont.PFSC_B(ofSize: 18)), .foreground(UIColor.brandMainColor))
        let c: ASAttributedString = .init("\n提供哪些服务", .font(UIFont.PFSC_B(ofSize: 18)), .foreground(UIColor.mainTextColor))
        label.attributed.text = a+b+c
        return label
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumInteritemSpacing = 8.0
        layout.minimumLineSpacing = 16
        
        let collectView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .clear
        // 注册自定义单元格
        collectView.register(YHServiceItemCell.self, forCellWithReuseIdentifier: YHServiceItemCell.cellReuseIdentifier)
        return collectView
    }()
    
    lazy var confirmBtn: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = .brandMainColor
        btn.titleLabel?.font = .PFSC_M(ofSize: 14)
        btn.setTitle("确认", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didConfirmBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "update_close"), for: .normal)
        btn.addTarget(self, action: #selector(didCloseBtnClicked), for: .touchUpInside)
        return btn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    func createUI() {
        
        self.addSubview(blackMaskView)
        self.addSubview(whiteContentView)
        self.addSubview(closeBtn)

        whiteContentView.addSubview(bgImgView)
        whiteContentView.addSubview(iconImgView)
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(confirmBtn)
        whiteContentView.addSubview(collectionView)
        whiteContentView.addSubview(confirmBtn)
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.equalTo(38)
            make.right.equalTo(-38)
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(-24)
        }
        
        bgImgView.snp.makeConstraints { make in
            make.left.right.top.equalTo(0)
            make.height.equalTo(153)
        }
        
        iconImgView.snp.makeConstraints { make in
            make.width.equalTo(102)
            make.height.equalTo(84)
            make.top.equalTo(16)
            make.right.equalTo(-16)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalTo(34)
            make.left.equalTo(18)
            make.right.equalTo(iconImgView.snp.left)
        }
        
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(iconImgView.snp.bottom).offset(20)
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.height.equalTo(0)
            make.bottom.equalTo(confirmBtn.snp.top).offset(-30)
        }
        
        confirmBtn.snp.makeConstraints { make in
            make.left.equalTo(16)
            make.right.equalTo(-16)
            make.bottom.equalTo(-16)
            make.height.equalTo(45)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.top.equalTo(whiteContentView.snp.bottom).offset(24)
            make.centerX.equalTo(whiteContentView)
        }
    }
    
    static func alertView() -> YHServiceSelectAlertView {
        let alertView = YHServiceSelectAlertView(frame: UIScreen.main.bounds)
        return alertView
    }
    
    @objc func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func didConfirmBtnClicked() {
        var ids = [Int]()
        for item in items {
            if item.isSelect {
                ids.append(item.id)
            }
        }
        confirmBlock?(ids)
        dismiss()
    }
    
    @objc func didCloseBtnClicked() {
        dismiss()
    }
    
}

extension YHServiceSelectAlertView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    // 返回单元格数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return items.count
    }
    
    // 返回每个单元格的大小
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        
        let width = floorl((KScreenWidth-54.0*2.0-10.0*2.0)/3.0)
        return CGSize(width: width, height: 42)
    }
    
    // 返回自定义单元格
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHServiceItemCell.cellReuseIdentifier, for: indexPath) as? YHServiceItemCell else { return UICollectionViewCell() }
        if 0 <= indexPath.item && indexPath.item < items.count {
            let item = items[indexPath.item]
            cell.updateItem(item)
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if 0 <= indexPath.item && indexPath.item < items.count {
            let item = items[indexPath.item]
            item.isSelect = !item.isSelect
            collectionView.reloadData()
        }
    }
}
