//
//  PartsApplyDeliveryVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/25.
//

import Foundation

class PartsApplyDeliveryVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var partsList:[M_PartsApplyDetail.Parts] = []
    
    var applyId = ""
    
    var deliverCompany = ""        //物流公司ID;
    var deliverCompanyName = ""        //物流公司名称;
    var deliverNo = ""           //物流单号;
    var deliverRemark = ""        //出库备注;
    
    var callBack:((Bool)->Void)?
}

extension PartsApplyDeliveryVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 8)
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("物流公司".languageString(), deliverCompanyName), config: (false, false, (8, [.topLeft, .topRight])), frameh: 48, didSelect:  {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.getDictItems("物流公司")
            })
            newForms.append(rowCell)
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationTextFieldCell>.init(data: ("物流单号".languageString(), deliverNo, UIKeyboardType.asciiCapable , true), frameh: 48) { [weak self] t in
                guard let weakSelf = self else { return }
                if let txt = t as? String {
                    weakSelf.deliverNo = txt
                }
                if let tag = t as? Int, tag == -999 {
                    let qrVC = QRViewController()
                    qrVC.configResultCall { code, errorStr in
                        if errorStr != nil && errorStr != "" {
                            CD.visibleVC?.promptInformation(errorStr ?? "扫码出错了~".languageString())
                            return
                        }
                        weakSelf.deliverNo = code ?? ""
                        weakSelf.makeForms()
                    }
                    let qrNavigationC = TWNavigationVc(rootViewController: qrVC)
                    qrNavigationC.modalPresentationStyle = .overFullScreen
                    qrNavigationC.modalTransitionStyle = .crossDissolve
                    CD.visibleVC?.present(qrNavigationC, animated: true, completion: nil)
                }
            }
            newForms.append(rowCell)
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationRemarkVCell>.init(data: ("出库备注".languageString(), deliverRemark), config: ((8, [.bottomLeft, .bottomRight]), true), frameh: 96) {[weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    weakSelf.deliverRemark = 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_PartsApplyDetail.Parts, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<PartsApplyOperationAmountsCell>.init(data: (data.outWarehouseName, data.invQty, data.checkQty, data.outQty), config: ("出库仓库".languageString(), "可用库存".languageString(), "已审数量".languageString(), "已出数量".languageString()),  frameh: 136)
        return [rowCell]
    }
    
    func makeQuantityCellForm(data:M_PartsApplyDetail.Parts,idx:Int) -> [TCCellBaseProtocol] {
        let maxQty1 = data.invQty.intValue()
        let maxQty2 = data.checkQty.intValue() - data.outQty.intValue()
        let maxQty = maxQty2 < maxQty1 ? maxQty2 : maxQty1
        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 PartsApplyDeliveryVm {
    
    func selectDictItems(_ str:String, datas:[[String:Any]]) {
        guard !datas.isEmpty else {
            hud_info("没有\(str)数据".languageString())
            return
        }
        let pickerDataArr = datas.compactMap {
            ($0.stringValue(forKey: "name"),"")
        }
        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.deliverCompany = dic.stringValue(forKey: "id")
            weakSelf.deliverCompanyName = dic.stringValue(forKey: "name")
            weakSelf.makeForms()
        }.show(CD.visibleVC!)
    }
}

extension PartsApplyDeliveryVm {
    func requestDatas() {
        var par:[String:Any] = [:]
        par["applyId"] = applyId

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/getApplyDelivery",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.partsList = data.arrayValue(forKey: "partsList").compactMap({M_PartsApplyDetail.Parts($0)})
                weakSelf.makeForms()
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
    
    func requestApplyDelivery() {
        var par:[String:Any] = [:]
        par["deliverCompany"] = deliverCompany
        par["deliverCompanyName"] = deliverCompanyName
        par["deliverNo"] = deliverNo
        par["deliverRemark"] = deliverRemark
        par["applyId"] = applyId
        par["partsList"] = partsList.compactMap({$0.operationJsonValue(typeStr: "outQty")})

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/applyDelivery",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 getDictItems(_ str:String) {
        var par:[String:Any] = [:]
        par["dictItemName"] = str

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/basicInformation/getDictItems",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: "list"))
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
}

