//
//  YHMakePlanModel.swift
//  galaxy
//
//  Created by EDY on 2025/4/1.
//  Copyright © 2025 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit
import SmartCodable

struct YHMakePlanModel: SmartCodable {
    var basic: [YHMakePlanMainModel] = []
    var work: [YHMakePlanMainModel] = []
    var live: [YHMakePlanMainModel] = []
    var invest: [YHMakePlanMainModel] = []
    
    // 修改所有子元素的 is_add_cart 值
    mutating func updateAddCartStatus() {
        basic = basic.map { $0.updatedModel() }
        work = work.map { $0.updatedModel() }
        live = live.map { $0.updatedModel() }
        invest = invest.map { $0.updatedModel() }
    }
}

struct YHMakePlanMainModel: SmartCodable {
    var product_id: Int = -1
    var cover_img: String = ""
    var product_name: String = ""
    var product_desc: String = ""
    var price: String = ""
    var is_add_cart: Bool = true
    var sub_product: [YHMakePlanSubModel] = []
    
    // 更新当前模型及其子模型的 is_add_cart 状态
    func updatedModel() -> YHMakePlanMainModel {
        var updatedModel = self
        updatedModel.is_add_cart = true

        // 处理子产品，找到最便宜的一个
        if !sub_product.isEmpty {
            // 找到最便宜的子产品
            let cheapestSubProduct = sub_product
                .sorted { ($0.price.toDouble() ?? 0) < ($1.price.toDouble() ?? 0) }
                .first
            
            // 更新所有子产品的 is_add_cart 状态
            updatedModel.sub_product = sub_product.map {
                var sub = $0
                sub.is_add_cart = ($0.product_id == cheapestSubProduct?.product_id)
                return sub
            }
        }
        
        return updatedModel
    }
}

struct YHMakePlanSubModel: SmartCodable {
    var product_id: Int = -1
    var cover_img: String = ""
    var product_name: String = ""
    var product_desc: String = ""
    var price: String = ""
    var is_add_cart: Bool = true
}

// 扩展 String 用于价格转换
extension String {
    func toDouble() -> Double? {
        // 移除可能存在的货币符号、千位分隔符等
        let numericString = self
            .replacingOccurrences(of: "$", with: "")
            .replacingOccurrences(of: ",", with: "")
            .trimmingCharacters(in: .whitespacesAndNewlines)
        
        return Double(numericString)
    }
}

extension YHMakePlanModel {
    
    mutating func toggleAddCartStatus(for productId: Int) {
        var localBasic = basic
        var localWork = work
        var localLive = live
        var localInvest = invest
        
        for i in 0..<localBasic.count {
            if localBasic[i].product_id != 0 && localBasic[i].product_id == productId {
                localBasic[i].is_add_cart = !localBasic[i].is_add_cart
                updateSubProducts(for: &localBasic[i])
                // Update the original arrays and return
                basic = localBasic
                work = localWork
                live = localLive
                invest = localInvest
                return
            }
        }
        
        for i in 0..<localWork.count {
            if localWork[i].product_id != 0 && localWork[i].product_id == productId {
                localWork[i].is_add_cart = !localWork[i].is_add_cart
                updateSubProducts(for: &localWork[i])
                // Update the original arrays and return
                basic = localBasic
                work = localWork
                live = localLive
                invest = localInvest
                return
            }
        }
        
        for i in 0..<localLive.count {
            if localLive[i].product_id != 0 && localLive[i].product_id == productId {
                localLive[i].is_add_cart = !localLive[i].is_add_cart
                updateSubProducts(for: &localLive[i])
                // Update the original arrays and return
                basic = localBasic
                work = localWork
                live = localLive
                invest = localInvest
                return
            }
        }
        
        for i in 0..<localInvest.count {
            if localInvest[i].product_id != 0 && localInvest[i].product_id == productId {
                localInvest[i].is_add_cart = !localInvest[i].is_add_cart
                updateSubProducts(for: &localInvest[i])
                // Update the original arrays and return
                basic = localBasic
                work = localWork
                live = localLive
                invest = localInvest
                return
            }
        }
                
        // If we get here, we need to check sub_products (product_id == 0 cases)
        checkSubProducts(in: &localBasic, for: productId)
        checkSubProducts(in: &localWork, for: productId)
        checkSubProducts(in: &localLive, for: productId)
        checkSubProducts(in: &localInvest, for: productId)
        basic = localBasic
        work = localWork
        live = localLive
        invest = localInvest
    }
    
    private mutating func updateSubProducts(for mainModel: inout YHMakePlanMainModel) {
        if mainModel.is_add_cart {
            // Find the subproduct with the lowest price
            if let cheapestIndex = mainModel.sub_product.enumerated().min(by: {
                let price1 = Double($0.element.price) ?? 0
                let price2 = Double($1.element.price) ?? 0
                return price1 < price2
            })?.offset {
                // Set only the cheapest to true, others to false
                for i in 0..<mainModel.sub_product.count {
                    mainModel.sub_product[i].is_add_cart = (i == cheapestIndex)
                }
            }
        } else {
            // If main model is not in cart, set all subproducts to false
            for i in 0..<mainModel.sub_product.count {
                mainModel.sub_product[i].is_add_cart = false
            }
        }
    }
    
    private mutating func checkSubProducts(in models: inout [YHMakePlanMainModel], for productId: Int) {
       for i in 0..<models.count {
           var hasFind = false
           for j in 0..<models[i].sub_product.count {
               if models[i].sub_product[j].product_id == productId {
                   if models[i].sub_product[j].is_add_cart {
                       models[i].sub_product[j].is_add_cart = false
                       models[i].is_add_cart = false
                   } else {
                       models[i].sub_product[j].is_add_cart = true
                       models[i].is_add_cart = true
                   }
                   hasFind = true
               }
           }
           if hasFind {
               for j in 0..<models[i].sub_product.count {
                   if models[i].sub_product[j].product_id == productId {
                       
                   } else {
                       models[i].sub_product[j].is_add_cart = false
                   }
               }
           }
       }
   }
    
    func calculateTotalPrice() -> String {
        let allCategories = [basic, work, live, invest]
        var total: Double = 0
        
        for category in allCategories {
            for mainModel in category {
                // Check main product
                if mainModel.is_add_cart, let price = Double(mainModel.price), mainModel.sub_product.count == 0 {
                    total += price
                }
                
                // Check sub products
                for subModel in mainModel.sub_product {
                    if subModel.is_add_cart, let price = Double(subModel.price) {
                        total += price
                    }
                }
            }
        }
        
        return "\(total)"
    }
}

extension YHMakePlanMainModel {
    /// Returns a filtered version of the model, keeping only `is_add_cart == true` for itself and its sub-products.
    func filteredByCartStatus() -> YHMakePlanMainModel? {
        guard is_add_cart else { return nil }
        
        var filteredModel = self
        filteredModel.sub_product = sub_product.filter { $0.is_add_cart }
        return filteredModel
    }
}

extension Array where Element == YHMakePlanMainModel {
    /// Filters out models where `is_add_cart == false` and also filters their sub-products.
    func filteredByCartStatus() -> [YHMakePlanMainModel] {
        self.compactMap { $0.filteredByCartStatus() }
    }
}

extension Array where Element == YHMakePlanSubModel {
    /// Filters out sub-models where `is_add_cart == false`.
    func filteredByCartStatus() -> [YHMakePlanSubModel] {
        self.filter { $0.is_add_cart }
    }
}

extension Array where Element == YHMakePlanSubModel {
    func indexOfLowestPrice() -> Int? {
        return self.enumerated().reduce(into: (index: 0, price: Double.infinity)) { result, current in
            let (currentIndex, model) = current
            if let currentPrice = Double(model.price), currentPrice < result.price {
                result = (currentIndex, currentPrice)
            }
        }.index
    }
}
