//
//  YHResignTemplateAlertView.swift
//  galaxy
//
//  Created by edy on 2024/9/14.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHResignTemplateSheetView: UIView {

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

    var templateArr: [YHResignTemplateItemModel] = []
    var templateInfo: YHResignTemplateDetail?
        
    var scanTemplateBlock: ((YHResignTemplateItemModel?) -> 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: YHResignTemplateDetail) {
        
        templateInfo = model
        if !model.getName().isEmpty {
            titleLabel.text = "\(model.getName())示例模板"
        }
        
        templateArr.removeAll()
        templateArr = model.file_url
        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() -> YHResignTemplateSheetView {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
        return self
    }
    
    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    @objc func didClickKnownBtn() {
        dismiss()
    }
}

extension YHResignTemplateSheetView: 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: 14)
        if 0 <= indexPath.row && indexPath.row < templateArr.count {
            cell.templateModel = 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)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 82.0
    }
    
    private func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> CGFloat {
    
        if let desc = templateInfo?.remark, !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?.remark, !desc.isEmpty {
            let label = UILabel()
            label.textColor = UIColor.mainTextColor(alpha: 0.7)
            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()
    }

}
