//
//  PartsInventorySearchVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/10/8.
//

import Foundation

class PartsInventorySearchVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var searchKey = ""
    var warehouseId = ""
    var warehouseName = ""
    
    var invList:[M_PartsInventory] = []         //配件明细

    var pageNumber = 1      //当前页
    var pageSize = 10        //每页大小
    var pageCount = 0
    
    var type = 0         //0配件库存；1服务商库存；2总部库存
    var selectedsiteId = ""     //选中服务商id
    var selectedsiteName = ""     //选中服务商名称
}

extension PartsInventorySearchVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 8)
        do{
            let rowCell = TCFormCellModel<OrderOperationTextFieldCell>.init(data: ("查询配件".languageString(), searchKey, UIKeyboardType.asciiCapable , true),config: (true, false,([.layerMinXMinYCorner, .layerMaxXMinYCorner],8) , true), frameh: 52) { [weak self] t in
                guard let weakSelf = self else { return }
                if let txt = t as? String {
                    weakSelf.searchKey = 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.searchKey = 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)
        }
        switch type {
        case 0:
            do{
                let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("服务商".languageString(), MyInfo.shareInstance().siteName), config: (false, true, (0, [])), frameh: 48)
                newForms.append(rowCell)
            }
        case 1:
            do{
                let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("服务商".languageString(), selectedsiteName), config: (false, false, (0, [])), frameh: 48, didSelect:  {[weak self] in
                    guard let weakSelf = self else { return }
                    weakSelf.getSiteData("服务商")
                })
                newForms.append(rowCell)
            }
        default:
            break
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("查询仓库".languageString(), warehouseName), config: (false, false, (0, [])), frameh: 48, didSelect:  {[weak self] in
                guard let weakSelf = self else { return }
                switch weakSelf.type {
                case 0:
                    weakSelf.getWarehosue("查询仓库", searchType: 2)
                case 1:
                    guard !weakSelf.selectedsiteId.isEmpty else {
                        hud_info("请选择服务商".languageString())
                        return
                    }
                    weakSelf.getWarehosue("查询仓库", searchType: 2)
                case 2:
                    weakSelf.getWarehosue("查询仓库", searchType: 3)
                default:
                    break
                }
            })
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, height: 12)
        do{
            let rowCell = TCFormCellModel<VTSubmitButtonCell>.init(frameh: UITableView.automaticDimension) { [weak self] _ in
                guard let weakSelf = self else { return }
                weakSelf.pageNumber = 1
                weakSelf.partsInvSearch()
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        
        for item in invList {
            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 += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        }
        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_PartsInventory, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<PartsApplyOperationAmountsCell>.init(data: (data.warehouseName, data.qty, data.takeUpQty, data.ageDate), config: ("仓库名称".languageString(), "库存量".languageString(), "占用量".languageString(), "库龄".languageString()),  frameh: 136)
        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 PartsInventorySearchVm {
    func selectDictItems(_ str:String, datas:[[String:Any]]) {
        guard !datas.isEmpty else {
            hud_info("没有\(str)数据".languageString())
            return
        }
        var pickerDataArr:[(String,String)] = []
        switch str {
        case "查询仓库":
            pickerDataArr = datas.compactMap {
                ($0.stringValue(forKey: "warehouseName"),"")
            }
        case "服务商":
            pickerDataArr = datas.compactMap {
                ($0.stringValue(forKey: "siteName"),"")
            }
        default:
            break
        }
        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]
            switch str {
            case "查询仓库":
                weakSelf.warehouseId = dic.stringValue(forKey: "warehouseId")
                weakSelf.warehouseName = dic.stringValue(forKey: "warehouseName")
            case "服务商":
                let siteId = dic.stringValue(forKey: "siteId")
                let siteName = dic.stringValue(forKey: "siteName")
                if weakSelf.selectedsiteId != siteId {
                    weakSelf.selectedsiteId = siteId
                    weakSelf.selectedsiteName = siteName
                    weakSelf.warehouseId = ""
                    weakSelf.warehouseName = ""
                }
            default:
                break
            }
            weakSelf.makeForms()
        }.show(CD.visibleVC!)
    }
}

extension PartsInventorySearchVm {
    
    func partsInvSearch() {
        var par:[String:Any] = [:]
        par["searchKey"] = searchKey
        par["warehouseId"] = warehouseId
        par["pageNumber"] = pageNumber
        par["pageSize"] = pageSize
        
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/parts/partsInvSearch",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_hidden()
            if let data = result["data"] as? [String:Any] {
                let invList = data.arrayValue(forKey: "invList")
                if weakSelf.pageNumber == 1 {
                    if invList.isEmpty {
                        hud_info("没有库存数据".languageString())
                    }
                    weakSelf.invList = invList.compactMap({M_PartsInventory($0)})
                }else{
                    weakSelf.invList += invList.compactMap({M_PartsInventory($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 getWarehosue(_ str:String, searchType:Int) {
        var par:[String:Any] = [:]
        par["searchType"] = searchType      //searchType:使用场景:1核销入库仓库;2服务商库存查询；3总部库存查询;
        if type == 1 {
            par["selectedSiteId"] = selectedsiteId
        }
        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] {
                let warehouseList = data.arrayValue(forKey: "warehouseList")
                if !warehouseList.isEmpty {
                    weakSelf.selectDictItems(str, datas: warehouseList)
                }else{
                    hud_info("没有查询仓库数据".languageString())
                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
    
    func getSiteData(_ str:String) {
        var par:[String:Any] = [:]
        par["pageSize"] = 999999
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/basicInformation/getSiteData",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_hidden()
            if let data = result["data"] as? [String:Any] {
                let siteList = data.arrayValue(forKey: "siteList")
                if !siteList.isEmpty {
                    weakSelf.selectDictItems(str, datas: siteList)
                }else{
                    hud_info("没有服务商数据".languageString())
                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()
    }
}

class M_PartsInventory: NSObject {
    var partsId = ""         // 配件ID);
    var pic = ""         //  图片,后台返回空值时,前端使用默认图片显示);
    var partsName = ""         //  配件名称);
    var partsCode = ""         //  配件编码);
    var warehouseName = ""         //  仓库名称);
    var qty = ""         //  库存量);
    var takeUpQty = ""         //  占用量);
    var ageDate = ""         //  库龄);
    
    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")
        warehouseName = data.stringValue(forKey: "warehouseName")
        qty = data.stringValue(forKey: "qty")
        takeUpQty = data.stringValue(forKey: "takeUpQty")
        ageDate = data.stringValue(forKey: "ageDate")
    }
}
