//
//  YHImproveSchemeTemplateListView.swift
//  galaxy
//
//  Created by Dufet on 2024/11/18.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHImproveSchemeTemplateListView: UIView {
    
    static func listView() -> YHImproveSchemeTemplateListView {
        let v = YHImproveSchemeTemplateListView(frame: UIScreen.main.bounds)
        return v
    }
    
    lazy var previewFileTool: YHFilePreviewTool = {
        let tool = YHFilePreviewTool(targetVC: UIViewController.current)
       return tool
    }()

    let bottomFixHeight = 102.0
    
    var items: [YHSchemeTemplatesModel] = [] {
        didSet {
            var totalHeight = bottomFixHeight+52.0
            for item in items {
               let height = getHeight(text: item.name)+32.0
               totalHeight += height
            }
            totalHeight = floorl(totalHeight)
            if totalHeight >= 628.0 {
                totalHeight = 628.0
            }
            whiteView.snp.updateConstraints { make in
                make.height.equalTo(totalHeight)
            }
            self.setNeedsLayout()
            self.layoutIfNeeded()
            tableView.reloadData()
        }
    }

    lazy var blackMaskView: UIView = {
        let view = UIView()
        view.backgroundColor = .alertMaskColor
        return view
    }()
    
    lazy var whiteView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        view.layer.cornerRadius = 4.0
        return view
    }()
    
    lazy var tableView: UITableView = {
        
        let tableView = UITableView(frame: .zero, style: .grouped)
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "UITableViewCell")
        tableView.register(YHImproveSchemeTemplateListCell.self, forCellReuseIdentifier: YHImproveSchemeTemplateListCell.cellReuseIdentifier)
        tableView.bounces = false
        return tableView
    }()
    
    lazy var titleLabel: UILabel = {
        let label = UILabel()
        label.textAlignment = .center
        label.font = UIFont.PFSC_M(ofSize: 17)
        label.textColor = .mainTextColor
        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)
        btn.YH_clickEdgeInsets = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
        return btn
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        createUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func show() {
        UIApplication.shared.yhKeyWindow()?.addSubview(self)
    }

    @objc func dismiss() {
        self.removeFromSuperview()
    }
    
    func createUI() {
        
        self.addSubview(blackMaskView)
        self.addSubview(whiteView)
        whiteView.addSubview(titleLabel)
        whiteView.addSubview(tableView)
        whiteView.addSubview(closeBtn)
        
        blackMaskView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        
        whiteView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(628)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(52)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.width.height.equalTo(24)
            make.centerY.equalTo(titleLabel)
            make.right.equalTo(-24)
        }
        
        tableView.snp.makeConstraints { make in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.bottom.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(0)
        }
    }
}

extension YHImproveSchemeTemplateListView: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if 0 <= indexPath.row && indexPath.row < items.count {
            let item = items[indexPath.row]
            guard let cell = tableView.dequeueReusableCell(withIdentifier: YHImproveSchemeTemplateListCell.cellReuseIdentifier, for: indexPath) as? YHImproveSchemeTemplateListCell else {
                return UITableViewCell()
            }
            cell.titleLabel.text = "\(indexPath.row+1)、\(item.name)"
            cell.model = item
            cell.clickBlock = {
                [weak self] model in
                guard let self = self else { return }
                if !model.url.isEmpty {
                    let viewModel = YHBaseViewModel()
                    if model.url.contains("pub.galaxy-immi.com") { // 资源文件
                        viewModel.getRealUsefulUrl(model.url) { success in
                            self.previewFileTool.openXLSXRemoteFile(urlString: success, fileName: "预览")
                        }
                    } else { // web
                        let vc = YHH5WebViewVC()
                        vc.url = model.url
                        vc.isFullScreenFlag = false
                        UIViewController.current?.navigationController?.pushViewController(vc)
                        self.dismiss()
                    }
                }
                
            }
            return cell
        }
        
        let defaultCell = tableView.dequeueReusableCell(withIdentifier: "UITableViewCell", for: indexPath)
        return defaultCell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView()
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return bottomFixHeight
    }
    
    func getHeight(text: String) -> CGFloat {
        
        let size = CGSize.init(width: KScreenWidth-115, height: CGFloat(MAXFLOAT))
        let dic = [NSAttributedString.Key.font: UIFont.PFSC_R(ofSize: 14)]
        let strSize = text.boundingRect(with: size, options: [.usesLineFragmentOrigin], attributes: dic, context: nil).size
        return CGSize(width: strSize.width, height: strSize.height).height
    }
}
