//
//  OldPartsToBeReturnedListVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/10/7.
//

import Foundation

class OldPartsToBeReturnedListVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var searchType = 0       //搜索类型(0所有;1待审核;2待发货;3待签收)
    var searchKey = ""      //查询关键字(搜索时传入的关键字)
    var pageNumber = 1      //当前页
    var pageSize = 10        //每页大小
    var pageCount = 0
    
    var models:[M_OldPartsToBeReturnedList] = []
    
    var callBack:((Bool)->Void)?
    
}

extension OldPartsToBeReturnedListVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        
//        for item in 0..<5{
//            newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
//            newForms += makeTitleCellForm(titleStr: "KH20230531230", statStr: "已结算", typeStr: "")
//            for part in 0..<4 {
//                newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white)
//                newForms += makeInfoCellForm(titleStr: "压缩机", detailStr: "x1")
//            }
//            let bool = true
//            newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: bool ? (0,[]) : (8,[.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: bool ? 8 : 16)
//            if bool {
//                newForms += makeBtnCellForm(idx: -98)
//            }
//        }
        
        
        for (i,item) in models.enumerated(){
            newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
            newForms += makeTitleCellForm(titleStr: item.orderNo, statStr: item.statName, typeStr: "")
            for part in item.partsList {
                newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white)
                newForms += makeInfoCellForm(titleStr: part.oldPartsName, detailStr: "x\(part.qty)")
            }
            let bool = item.returnButton == 1
            newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: bool ? (0,[]) : (8,[.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: bool ? 8 : 16)
            if bool {
                newForms += makeBtnCellForm(idx: i)
            }
        }
        newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 16)
        
        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, didSelect:  {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.didSelect(idx)
        })
        return [rowCell]
    }
    
    func makeTitleCellForm(titleStr:String, statStr:String, typeStr:String, idx:Int = -99) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<PartsManagementListTitleCell>.init(data: (titleStr, statStr, typeStr), config: UIColor.clear, frameh: UITableView.automaticDimension, didSelect:  {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.didSelect(idx)
        })
        return [rowCell]
    }
    
    func makeInfoCellForm(titleStr:String, detailStr:String, idx:Int = -99) -> [TCCellBaseProtocol] {
        let ww = titleStr.getLabelWidth(h: 20, f: Config.font.fontRegular(14)) + 8
        let rowCell = TCFormCellModel<PartsManagementListInfoCell>.init(data: (titleStr, detailStr),config: (ww, Config.color.hex("3"), Config.color.hex("9")), frameh: UITableView.automaticDimension, didSelect:  {[weak self] in
            guard let weakSelf = self else { return }
            weakSelf.didSelect(idx)
        })
        return [rowCell]
    }
    
    func makeBtnCellForm(idx:Int = -99) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OldPartsListButtonsCell>.init(frameh: UITableView.automaticDimension, callBack: { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.didSelect(idx)
        })
        return [rowCell]
    }
    
    func didSelect(_ idx:Int) {
        guard idx >= 0 else {
            return
        }
        let m = models[idx]
        R_OldPartsConfirmReturn.router(m.orderId, partsList: m.partsList) { [weak self] bool in
            guard let weakSelf = self else { return }
            weakSelf.callBack?(bool)
        }
    }
}
extension OldPartsToBeReturnedListVm {
    func requestData() {
        var par:[String:Any] = [:]
//        par["searchType"] = searchType
        par["searchKey"] = searchKey
        par["pageNumber"] = pageNumber
        par["pageSize"] = pageSize

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/parts/waitReturnOrderSearch",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: "waitReturnList").compactMap({M_OldPartsToBeReturnedList($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()
    }
}
