//
//  HomeTitleCollectionModel.swift
//  PhoneManager
//
//  Created by edy on 2025/3/26.
//

import Foundation
import AVFoundation

func loadChargeImtesSONFromBundle() -> [ChargeViewCollectionModel]? {
    // 获取 JSON 文件路径
    guard let path = Bundle.main.path(forResource: "ChargeItemsData", ofType: "json") else {
        print("未找到 JSON 文件")
        return nil
    }
    
    do {
        // 读取文件内容
        let data = try Data(contentsOf: URL(fileURLWithPath: path))
        
        // 解析 JSON 数据
        let decoder = JSONDecoder()
        let items = try decoder.decode([ChargeViewCollectionModel].self, from: data)
        return items
    } catch {
        print("解析 JSON 失败：\(error)")
        return nil
    }
}

func loadVideoItems() -> [ChargeDataModel]{
    let mainBundle = Bundle.main
    // 获取指定文件夹下所有 MP4 文件的 URL
    var dataArray : [ChargeDataModel] = []
    if let mp4URLs = mainBundle.urls(forResourcesWithExtension: "mp4", subdirectory: nil) {
        for url in mp4URLs {
            let asset = AVURLAsset(url: url)
            // 获取视频第一帧图片
            let imageGenerator = AVAssetImageGenerator(asset: asset)
            imageGenerator.appliesPreferredTrackTransform = true
            let time = CMTimeMake(value: 0, timescale: 1)
            do {
                let cgImage = try imageGenerator.copyCGImage(at: time, actualTime: nil)
                let image = UIImage(cgImage: cgImage)
                let model = ChargeDataModel(isFree: false, coverImage: image, url: url)
                dataArray.append(model)
            } catch {
                print("获取视频图片出错: \(error.localizedDescription)")
            }
        }
    }
    
    // 需要添加一张默认背景
    let model = ChargeDataModel(isFree: true, coverImage: UIImage(named: "img_bj_battery_default")!, url: URL("")!)
    dataArray.insert(model, at: 0)
    return dataArray
}

struct ChargeViewCollectionModel:Codable {
    
    var isFree:Bool
    var CoverImage:String
    var filePath:String
    
    enum Category: String, Codable {
        case isFree,CoverImage,filePath
    }
}
