//
//  YHCertificateFilterView.swift
//  galaxy
//
//  Created by edy on 2024/3/13.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

enum YHCertificateFilterType: Int {
    // 类型
    case certificate = 0
    case degree = 1
    case employmentProof = 2
    case other = 3
    // 状态
    case preUpload = 4
    case rejected = 5
    case review = 6
    case finish = 7

}

class YHCertificateFilterSectionInfo {
    var title: String
    var items: [YHCertificateFilterItem]
    
    init(title: String, items:[YHCertificateFilterItem]) {
        self.title = title
        self.items = items
    }
}

class YHCertificateFilterItem {
    var type: YHCertificateFilterType
    var title: String
    var isSelected: Bool = false
    var tag:Int {
        if type.rawValue < 4 {
            return type.rawValue
        }
        if type == .preUpload {
            return YHCertificateUploadStatus.preUpload.rawValue
        } else if type == .rejected {
            return YHCertificateUploadStatus.rejected.rawValue
        } else if type == .review {
            return YHCertificateUploadStatus.review.rawValue
        } else if type == .finish {
            return YHCertificateUploadStatus.finish.rawValue
        }
        return -1
    }
    init(type: YHCertificateFilterType, title: String) {
        self.type = type
        self.title = title
    }
}


class YHCertificateFilterView: UIView {
     
    static let margin = 21.0
    static let gap = 12.0
    static let itemHeight = 36.0
    var confirmBlock:(([String : String])->())?
    var items:[YHCertificateFilterSectionInfo] = [
        
        YHCertificateFilterSectionInfo(title: "类型".local, items: [YHCertificateFilterItem(type: .certificate, title: "证件"),
                                                                   YHCertificateFilterItem(type: .degree, title: "学历"),
                                                                   YHCertificateFilterItem(type: .employmentProof, title: "工作证明"),
                                                                   YHCertificateFilterItem(type: .other, title: "其他"),
                                                                 ]),
        YHCertificateFilterSectionInfo(title: "状态".local, items: [YHCertificateFilterItem(type: .preUpload, title: "待上传"),
                                                                   YHCertificateFilterItem(type: .rejected, title: "已驳回"),
                                                                   YHCertificateFilterItem(type: .review, title: "审核中"),
                                                                   YHCertificateFilterItem(type: .finish, title: "已完成"),
                                                                 ])]
    
    lazy var collectionView: UICollectionView = {
        // 设置布局方向
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.minimumInteritemSpacing = Self.gap
        flowLayout.minimumLineSpacing = Self.gap
        flowLayout.scrollDirection = .vertical
        
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collectionView.contentInset = UIEdgeInsets(top: 0, left: Self.margin, bottom: 0, right: Self.margin)
        collectionView.backgroundColor = UIColor.white
        collectionView.register(YHCertificateFilterItemCell.self, forCellWithReuseIdentifier:YHCertificateFilterItemCell.cellReuseIdentifier)
        collectionView.register(YHCertificateFilterTypeView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: YHCertificateFilterTypeView.reuseIdentifier)
        collectionView.delegate = self
        collectionView.dataSource = self
        return collectionView
    }()

    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
        return view
    }()
    
    lazy var topLine:UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        return view
    }()
    
    lazy var bottomLine:UIView = {
        let view = UIView()
        view.backgroundColor = .separatorColor
        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 bottomView: UIView = {
        let view = UIView()
        return view
    }()
    
    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
    }()
    
    lazy var resetBtn:UIButton = {
        let btn = UIButton()
        btn.setTitle("重置", for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 14)
        btn.setTitleColor(UIColor.mainTextColor, for: .normal)
        btn.backgroundColor = UIColor(hexString:"#F8F9FB")
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickResetBtn), for: .touchUpInside)
        return btn
    }()
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    static func sheetView() -> YHCertificateFilterView {
        let sheetView = YHCertificateFilterView(frame:UIScreen.main.bounds)
        return sheetView
    }
    
    func createUI() {
        
        self.addSubview(blackMaskView)
        self.addSubview(whiteContentView)
        
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect:bounds,byRoundingCorners: corner,cornerRadii:CGSizeMake(8.0, 8.0));
        let layer = CAShapeLayer();
        layer.frame = whiteContentView.bounds;
        layer.path = path.cgPath;
        whiteContentView.layer.mask = layer;
        
        whiteContentView.addSubview(titleLabel)
        whiteContentView.addSubview(closeBtn)
        whiteContentView.addSubview(topLine)
        whiteContentView.addSubview(bottomView)
        whiteContentView.addSubview(collectionView)

        bottomView.addSubview(bottomLine)
        bottomView.addSubview(resetBtn)
        bottomView.addSubview(confirmBtn)

        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(450 + k_Height_safeAreaInsetsBottom())
        }
        
        titleLabel.snp.makeConstraints { make in
            make.height.equalTo(52)
            make.left.right.top.equalToSuperview()
        }
        
        closeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.right.equalToSuperview().offset(-20)
            make.width.height.equalTo(24)
        }
        
        topLine.snp.makeConstraints { make in
            make.height.equalTo(1)
            make.top.equalTo(titleLabel.snp.bottom)
            make.left.equalToSuperview().offset(21)
            make.right.equalToSuperview().offset(-21)
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(topLine.snp.bottom)
            make.bottom.equalTo(bottomView.snp.top)
        }

        
        bottomView.snp.makeConstraints { make in
            make.height.equalTo(68)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-k_Height_safeAreaInsetsBottom())
        }
        
        bottomLine.snp.makeConstraints { make in
            make.height.equalTo(1)
            make.top.left.right.equalToSuperview()
        }
        
        resetBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(44)
            make.width.equalTo(86)
            make.centerY.equalToSuperview()
        }
        
        confirmBtn.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(resetBtn.snp.right).offset(10)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(44)
            make.centerY.equalToSuperview()
        }
    }
}

extension YHCertificateFilterView {
    
    func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func didClickConfirmBtn() {
        
        var statusValues:[String] = []
        var typeValues:[String] = []
        
        for sectionInfo in items {
            for item in sectionInfo.items {
                if item.isSelected {
                    if sectionInfo.title == "类型".local {
                        typeValues.append("\(item.tag)")
                    } else if sectionInfo.title == "状态".local {
                        statusValues.append("\(item.tag)")
                    }
                }
            }
        }
        let statusStr = statusValues.joined(separator: ",")
        let typeStr = typeValues.joined(separator: ",")
        let dict:[String : String] = [ "status_all": statusStr,
                                       "template_cate_id": typeStr]
        print(dict)
        if let confirmBlock = confirmBlock {
            confirmBlock(dict)
        }
        dismiss()
    }
    
    @objc func didClickResetBtn() {
        for sectionInfo in items {
            for item in sectionInfo.items {
                item.isSelected = false
            }
        }
        collectionView.reloadData()
    }
}

extension YHCertificateFilterView:UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return items.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if 0 <= section && section < items.count {
            let sectionInfo = items[section]
            return sectionInfo.items.count
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        var width = Double(KScreenWidth-Self.margin*2.0-Self.gap*3.0)
        width = floor(width/4.0)
        return CGSize(width:width, height: Self.itemHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection:Int) -> CGSize {
        
        return CGSize(width: KScreenWidth, height: 57)
    }
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        if kind == UICollectionView.elementKindSectionHeader {
            let headerView: YHCertificateFilterTypeView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: YHCertificateFilterTypeView.reuseIdentifier, for: indexPath) as! YHCertificateFilterTypeView
            
            if 0 <= indexPath.section && indexPath.section < items.count {
                let sectionInfo = items[indexPath.section]
                headerView.title = sectionInfo.title
            }
            return headerView
        }
        return UICollectionReusableView()
    }
        
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: YHCertificateFilterItemCell.cellReuseIdentifier, for: indexPath) as! YHCertificateFilterItemCell
        
        if 0 <= indexPath.section && indexPath.section < items.count {
            let sectionInfo = items[indexPath.section]
            if 0 <= indexPath.row && indexPath.row < sectionInfo.items.count {
                let item = sectionInfo.items[indexPath.row]
                cell.title = item.title
                cell.isSelect = item.isSelected
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if 0 <= indexPath.section && indexPath.section < items.count {
            let sectionInfo = items[indexPath.section]
            if 0 <= indexPath.row && indexPath.row < sectionInfo.items.count {
                let item = sectionInfo.items[indexPath.row]
                item.isSelected = !item.isSelected
            }
            collectionView.reloadData()
        }
    }
}

class YHCertificateFilterTypeView: UICollectionReusableView {
    
    static let reuseIdentifier = "YHCertificateFilterTypeView"
    
    var title: String? {
        didSet {
            titleLabel.text = title
        }
    }
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .left
        label.font = UIFont.PFSC_M(ofSize:14)
        label.text = "类型"
        return label
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    func createUI() {
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
