//
//  YHCertificateTemplateView.swift
//  galaxy
//
//  Created by edy on 2024/3/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//
/*
 【Usage】
 let view = YHCertificateTemplateView.templateView(templateInfo)
 view.scanTemplateBlock = {
     [weak self] temlateInfo in
     guard let self = self else { return }
 }
 view.show()
 */

import UIKit

class YHCertificateTemplateSheetView: UIView {

    static func templateView(_ model: YHTemplateInfo) -> YHCertificateTemplateSheetView {
        let sheetView = YHCertificateTemplateSheetView(frame: UIScreen.main.bounds)
        sheetView.updateModel(model)
        return sheetView
    }

    var templateArr: [YHMaterialPath] = []
    var templateInfo: YHTemplateInfo?
        
    var scanTemplateBlock: ((YHMaterialPath?) -> Void)?
    
    lazy var blackMaskView: UIView = {
        let view = UIView()
        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 topView: UIView = {
        let view = UIView()
        view.addSubview(titleLabel)
        view.addSubview(closeBtn)
        
        let line = UIView()
        line.backgroundColor = .separatorColor
        view.addSubview(line)
        
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.left.equalToSuperview().offset(64)
            make.right.equalToSuperview().offset(-64)
            make.bottom.equalToSuperview().offset(-12)
        }
        closeBtn.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-20)
            make.width.height.equalTo(24)
        }
        closeBtn.YH_clickEdgeInsets = UIEdgeInsets(top: 15, left: 15, bottom: 15, right: 15)
        line.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(1)
            make.bottom.equalToSuperview()
        }
        return view
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)

        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.estimatedSectionHeaderHeight = 20.0
        tableView.estimatedSectionFooterHeight = 1.0
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = .white
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHCertificateTemplateCell.self, forCellReuseIdentifier: YHCertificateTemplateCell.cellReuseIdentifier)
        return tableView
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.mainTextColor
        label.textAlignment = .center
        label.font = UIFont.PFSC_B(ofSize: 17)
        label.numberOfLines = 0
        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 knowBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("知道了".local, for: .normal)
        btn.titleLabel?.font = UIFont.PFSC_M(ofSize: 16)
        btn.setTitleColor(.white, for: .normal)
        btn.backgroundColor = UIColor.brandMainColor
        btn.layer.cornerRadius = kCornerRadius3
        btn.addTarget(self, action: #selector(didClickKnownBtn), 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 updateModel(_ model: YHTemplateInfo) {
        
        templateInfo = model
        if !model.name.isEmpty {
            titleLabel.text = "\(model.name)示例模板"
        }
        
        templateArr.removeAll()
        
        if model.materialPath.count > 0 {
            let template = model.materialPath[0]
            template.type = 0
            templateArr.append(template)
        }
        if model.guideFilePath.count > 0 {
            let guide = model.guideFilePath[0]
            guide.type = 1
            templateArr.append(guide)
        }
        self.tableView.reloadData()
        
        self.setNeedsLayout()
        self.layoutIfNeeded()
    }
    
    func createUI() {
        
        self.addSubview(blackMaskView)
        self.addSubview(whiteContentView)
        whiteContentView.addSubview(topView)
        whiteContentView.addSubview(knowBtn)
        whiteContentView.addSubview(tableView)
        
        let corner = UIRectCorner(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue)
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corner, cornerRadii: CGSize(width: kCornerRadius6, height: kCornerRadius6))
        let layer = CAShapeLayer()
        layer.frame = whiteContentView.bounds
        layer.path = path.cgPath
        whiteContentView.layer.mask = layer
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        whiteContentView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(484)
        }
        topView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
        }
        
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(topView.snp.bottom).offset(20)
            make.bottom.equalTo(knowBtn.snp.top).offset(-8)
        }

        knowBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(16)
            make.right.equalToSuperview().offset(-16)
            make.height.equalTo(48.0)
            make.bottom.equalToSuperview().offset(-8-k_Height_safeAreaInsetsBottom())
        }
    }
    
    func show() -> YHCertificateTemplateSheetView {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
        return self
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func didClickKnownBtn() {
        dismiss()
    }
}

extension YHCertificateTemplateSheetView: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return templateArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: YHCertificateTemplateCell.cellReuseIdentifier, for: indexPath) as? YHCertificateTemplateCell else {
            return UITableViewCell()
        }
        cell.update(bottomMargin: 20)
        if 0 <= indexPath.row && indexPath.row < templateArr.count {
            cell.templatePath = templateArr[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if 0 <= indexPath.row && indexPath.row < templateArr.count {
            let path = templateArr[indexPath.row]
            scanTemplateBlock?(path)
            dismiss()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 82.0
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
    
        if let desc = templateInfo?.description, !desc.isEmpty {
            return UITableView.automaticDimension
        }
        return 0.0
    }
    
    private func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> CGFloat {
    
        return 1.0
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView()
        if section == 0, let desc = templateInfo?.description, !desc.isEmpty {
            let label = UILabel()
            label.textColor = UIColor.mainTextColor
            label.textAlignment = .left
            label.font = UIFont.PFSC_R(ofSize: 14)
            label.numberOfLines = 0
            label.text = "注意事项:\n\(desc)"
            view.addSubview(label)
            
            label.snp.makeConstraints { make in
                make.top.equalToSuperview()
                make.left.equalToSuperview().offset(20)
                make.right.equalToSuperview().offset(-20)
                make.bottom.equalToSuperview().offset(-20)
           }
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }

}
