//
//  PartsReturnInVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/27.
//

import Foundation

class PartsReturnInVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var partsList:[M_PartsReturnDetail.Parts] = []
    
    var returnId = ""
    
    var inWarehouseId = ""        //入库仓ID;
    var inWarehouseName = ""        //入库仓名称
    var inRemark = ""        //核销备注
    
    var callBack:((Bool)->Void)?
}

extension PartsReturnInVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 8)
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("入库仓库".languageString(), inWarehouseName), config: (false, false, (8, [.topLeft, .topRight])), frameh: 48, didSelect:  {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.getWarehosue("入库仓库")
            })
            newForms.append(rowCell)
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationRemarkVCell>.init(data: ("核销备注".languageString(), inRemark), config: ((8, [.bottomLeft, .bottomRight]), true), frameh: 96) {[weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    weakSelf.inRemark = txt
                    weakSelf.makeForms()
                }
            }
            newForms.append(rowCell)
        }
        for (i, item) in partsList.enumerated() {
            newForms += makeLineCellForm(height: 8)
            newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMinXMinYCorner, .layerMaxXMinYCorner]),height: 12)
            newForms += makeItemCellForm(imgStr: item.pic, name: item.partsName, code: item.partsCode)
            newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, height: 6)
            newForms += makeAmountCellForm(data: item)
            newForms += makeOperationLineCellForm(contentColor: .clear, left3: 0, hh: 9)
            newForms += makeQuantityCellForm(data: item, idx: i)
        }
        newForms += makeLineCellForm(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 = 12) -> [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 makeItemCellForm(imgStr:String, name:String, code:String) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<PartsApplyOperationItemCell>.init(data: (imgStr, name, code),  frameh: UITableView.automaticDimension)
        return [rowCell]
    }
    
    func makeAmountCellForm(data:M_PartsReturnDetail.Parts, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<PartsApplyOperationAmountsCell>.init(data: (data.returnQty, data.inQty, "", ""), config: ("退回数量".languageString(), "已核销量".languageString(), "", ""),  frameh: 68)
        return [rowCell]
    }
    
    func makeQuantityCellForm(data:M_PartsReturnDetail.Parts,idx:Int) -> [TCCellBaseProtocol] {
        let maxQty = data.returnQty.intValue() - data.inQty.intValue()
        let rowCell = TCFormCellModel<PartsApplyOperationQuantityCell>.init(data: ("\("本次入库核销".languageString())：", data.qty, maxQty), config: (8, [.bottomRight, .bottomRight]),frameh: UITableView.automaticDimension) { [weak self] back in
            guard let weakSelf = self else { return }
            if let qty = back as? Int {
                weakSelf.partsList[idx].qty = qty
                weakSelf.makeForms()
            }
        }
        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 PartsReturnInVm {
    
    func selectDictItems(_ str:String, datas:[[String:Any]]) {
        guard !datas.isEmpty else {
            hud_info("没有\(str)数据".languageString())
            return
        }
        let pickerDataArr = datas.compactMap {
            ($0.stringValue(forKey: "warehouseName"),"")
        }
        TWSheetPicker.showActionSheet(titleStr: "请选择\(str)".languageString(), singleType: true, dataArr: pickerDataArr) {  [weak self] (indexArr) in
            guard let weakSelf = self else { return }
            guard let index = indexArr.first else { return }
            let dic = datas[index]
            weakSelf.inWarehouseId = dic.stringValue(forKey: "warehouseId")
            weakSelf.inWarehouseName = dic.stringValue(forKey: "warehouseName")
            weakSelf.makeForms()
        }.show(CD.visibleVC!)
    }
}

extension PartsReturnInVm {
    
    func requestApplyDelivery() {
        var par:[String:Any] = [:]
        par["inWarehouseId"] = inWarehouseId
        par["inWarehouseName"] = inWarehouseName
        par["inRemark"] = inRemark
        par["returnId"] = returnId
        par["partsList"] = partsList.compactMap({$0.operationJsonValue(typeStr: "inQty")})

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/returnIn",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_succeed("操作成功~".languageString())
            weakSelf.callBack?(true)
            CD.pop()
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
    
    func getWarehosue(_ str:String) {
        var par:[String:Any] = [:]
        par["searchType"] = 1      //searchType:使用场景:1核销入库仓库;2服务商库存查询；3总部库存查询;

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/basicInformation/getWarehosue",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_hidden()
            if let data = result["data"] as? [String:Any] {
                weakSelf.selectDictItems(str, datas: data.arrayValue(forKey: "warehouseList"))
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
}
