//
//  OrderDetailInfoVc.swift
//  VattiCSS
//
//  Created by WZR on 2023/8/28.
//

import UIKit
import JXSegmentedView
import MJRefresh

class OrderDetailInfoVc: UIViewController {
    @IBOutlet weak var tableView: UITableView!
    
    var vm = OrderDetailInfoVm()
    
    var getDatas:(()->Void)?
    var refreshDatas:(()->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        makeUI()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if vm.viewType == 1 {
            getDatas?()
            vm.makeForms()
        }
    }

    func makeUI() {
        
        vm.reloadData = {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.tableView.mj_header.endRefreshing()
            weakSelf.tableView.reloadData()
        }

        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
        }
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        let header = MJRefreshNormalHeader()
        header.stateLabel.textColor = UIColor(hexString: "999999")
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        tableView.mj_header = header
    }
    
    @objc func headerRefresh(){
        tableView.mj_header.endRefreshing()
        refreshDatas?()
    }
}

extension OrderDetailInfoVc: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return vm.forms.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellVM = vm.forms[indexPath.row]
        let cellIdentifier = cellVM.cellId.isEmpty ? String(describing: cellVM.cellClass) : cellVM.cellId
        var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        if cell == nil {
            let bundle = Bundle.main.path(forResource:cellIdentifier, ofType: "nib")
            if bundle == nil{
                tableView.register(cellVM.cellClass, forCellReuseIdentifier: cellIdentifier)
            }else{
                let cellNib = UINib(nibName:cellIdentifier, bundle: nil)
                tableView.register(cellNib, forCellReuseIdentifier: cellIdentifier)
            }
            cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
        }
        
        guard let endCell = cell else {
            fatalError("没有找到标识为：\(cellIdentifier)的Cell")
        }
        cellVM.bind(endCell)
        return endCell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = UIColor.init(hexString: "f8f8f8")
        return view
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellVM = vm.forms[indexPath.row]
        return cellVM.frameH
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellVM = vm.forms[indexPath.row]
        cellVM.tapBlock?()
    }
}

extension OrderDetailInfoVc:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return self.view
    }
}

extension OrderDetailInfoVc {
    class UICollectionViewLeftFlowLayout: UICollectionViewFlowLayout {
        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            guard let attrsArry = super.layoutAttributesForElements(in: rect) else {
                return nil
            }
            for i in 0..<attrsArry.count {
                if i != attrsArry.count-1 {
                    let curAttr = attrsArry[i] //当前attr
                    let nextAttr = attrsArry[i+1]  //下一个attr
                    //如果下一个在同一行则调整，不在同一行则跳过
                    if curAttr.frame.minY == nextAttr.frame.minY {
                        if nextAttr.frame.minX - curAttr.frame.maxX > minimumInteritemSpacing{
                            var frame = nextAttr.frame
                            let x = curAttr.frame.maxX + minimumInteritemSpacing
                            frame = CGRect(x: x, y: frame.minY, width: frame.width, height: frame.height)
                            nextAttr.frame = frame
                        }
                    }
                }
            }
            return attrsArry
        }
    }
    
    func getTextWidth(_ text:String ,_ font:UIFont ) -> CGFloat{
        
        let range = NSMakeRange(0, NSString(string: text).length)
        let attStr = NSMutableAttributedString(string: text as String)
        attStr.addAttribute(NSAttributedString.Key.font, value: font , range:range )
        //attStr.addAttribute(NSKernAttributeName, value: 1, range: range)
        
        let paraStyle = NSMutableParagraphStyle()
        paraStyle.lineSpacing = 5
        attStr.addAttribute(NSAttributedString.Key.paragraphStyle, value: paraStyle, range: range)
        
        let size = CGSize(width: CGFloat.greatestFiniteMagnitude, height: 40) ;
        let label = UILabel(frame: CGRect.zero);
        label.attributedText = attStr
        label.sizeToFit()
        
        let resultSize = label.sizeThatFits(size);
        return resultSize.width ;
    }
}
