//
//  PartsBomSearchVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/10/9.
//

import Foundation

class PartsBomSearchVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var searchKey = ""      //查询关键字(搜索时传入的关键字)
    var pageNumber = 1      //当前页
    var pageSize = 10        //每页大小
    var pageCount = 0
    
    var models:[M_PartsBom] = []
    
    var callBack:((Bool)->Void)?
    
}

extension PartsBomSearchVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        
        for item in models{
            newForms += makeTitleCellForm(titleStr: "\("产品型号".languageString())：\(item.itemName)", corner: (8, item.bomList.isEmpty ? .allCorners : [.topLeft, .topRight]))
            for (j, bom) in item.bomList.enumerated() {
                newForms += makeOperationLineCellForm(lineColor: .clear, corner: (8, [.topLeft, .topRight], 2))
                newForms += makeItemCellForm(imgStr: bom.pic, name: bom.partsName, code: bom.partsCode)
                newForms += makeOperationLineCellForm(lineColor: .clear, hh: 6)
                newForms += makeAmountCellForm(data: bom, hh: 68)
                newForms += makeOperationLineCellForm(lineColor: .clear, corner: (8, [.bottomLeft, .bottomRight], 2))
                
                if j < item.bomList.count - 1 {
                    newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, height: 8)
                }else{
                    newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
                }
            }
            newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
        }
        
        forms = newForms
        reloadData?()
    }
    
    func makeLineCellForm(leftW:CGFloat = 0, rightW:CGFloat = 0, bgColor:UIColor = .clear, backGroundColor:UIColor = .clear, corners:(CGFloat, CACornerMask) = (0, []), height:CGFloat = 8, idx:Int = -99) -> [TCCellBaseProtocol] {
        let uiConfigModel = TCFormCellConfigModel.defaultModel()
            .bgColor(backGroundColor)
            .cornerMask(corners.1)
            .cornerRadius(corners.0)
        let rowCell = TCFormCellModel<TCLineCell>.init(data: (leftW, rightW, bgColor), config: uiConfigModel, frameh: height)
        return [rowCell]
    }
    
    func makeTitleCellForm(titleStr:String, statusStr:String = "", corner:(CGFloat, UIRectCorner) = (0,[]), isShowArrow:Bool = false, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailTitleCell>.init(data: (titleStr, statusStr), config: (corner, isShowArrow, false), frameh: hh ?? UITableView.automaticDimension)
        return [rowCell]
    }
    
    func makeItemCellForm(imgStr:String, name:String, code:String) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderPartsApplyListItemCell>.init(data: (imgStr, name, code),  frameh: UITableView.automaticDimension)
        return [rowCell]
    }
    
    func makeAmountCellForm(data:M_PartsBom.BOM, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderPartsApplyListItemAmountCell>.init(data: (data),  frameh: hh == nil ? UITableView.automaticDimension : hh!)
        return [rowCell]
    }
    
    func makeOperationLineCellForm(cellColor:UIColor = .clear, bgColor:UIColor = .white, contentColor:UIColor = Config.color.hex("f8"), lineColor:UIColor = Config.color.hex("e6"), left1:CGFloat = 12, left2:CGFloat = 12, left3:CGFloat = 12, corner:(CGFloat, UIRectCorner, Int) = (0,[],3), hh:CGFloat = 12) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderOperationLineCell>.init(data: (cellColor, bgColor, contentColor, lineColor ), config: (left1, left2, left3, corner),frameh: hh)
        return [rowCell]
    }
}
extension PartsBomSearchVm {
    func requestData() {
        var par:[String:Any] = [:]
        par["searchKey"] = searchKey
        par["pageNumber"] = pageNumber
        par["pageSize"] = pageSize

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/parts/bomSearch",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                let waitReturnList = data.arrayValue(forKey: "itemList").compactMap({M_PartsBom($0)})
                if weakSelf.pageNumber == 1 {
                    weakSelf.models = waitReturnList
                }else{
                    weakSelf.models += waitReturnList
                }
                weakSelf.makeForms()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
}

class M_PartsBom: NSObject {
    var itemName = ""           //产品型号
    var bomList:[BOM] = []           //bom列表
    
    init(_ data:[String:Any]) {
        itemName = data.stringValue(forKey: "itemName")
        bomList = data.arrayValue(forKey: "bomList").compactMap({BOM($0)})
    }
    
    struct BOM {
        var partsId = ""           //配件ID
        var pic = ""           //图片,后台返回空值时,前端使用默认图片显示
        var partsName = ""           //配件名称
        var partsCode = ""           //配件编码
        var userPrice = ""           //用户价
        var maxQty = ""           //使用量
        var invQty = ""           //我的库存
        
        init(_ data:[String:Any]) {
            partsId = data.stringValue(forKey: "partsId")
            pic = kGetServerPicUrl(data.stringValue(forKey: "pic"))
            partsName = data.stringValue(forKey: "partsName")
            partsCode = data.stringValue(forKey: "partsCode")
            userPrice = data.stringValue(forKey: "userPrice")
            maxQty = data.stringValue(forKey: "maxQty")
            invQty = data.stringValue(forKey: "invQty")
        }
    }
}
