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

import Foundation

class OldPartsConfirmReturnVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var orderId = ""    //工单ID(必传)
    var deliverType = ""               //配送方式ID;
    var deliverTypeName = ""            //配送方式名称;
    
    var deliverCompany = ""        //物流公司ID;
    var deliverCompanyName = ""        //物流公司名称;
    var deliverNo = ""           //物流单号;
    var deliverRemark = ""        //退回备注;
    
    var returnList:[M_OldPartsToBeReturnedList.Parts] = []         //配件明细

    var callBack:((Bool)->Void)?
    
    var picArr:[TCFormImageModel] = []
    
    lazy var picker:TWImagePicker = {
        let pp = TWImagePicker()
        pp.maxPhotoCount = 3
        pp.isSheet = true
        return pp
    }()
}

extension OldPartsConfirmReturnVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 8)
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("配送方式".languageString(), deliverTypeName), config: (false, false, (8, [.topLeft, .topRight])), frameh: 52, didSelect:  {[weak self] in
                guard let weakSelf = self else { return }
                weakSelf.getDictItems("配送方式")
            })
            newForms.append(rowCell)
        }
        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: ((0, []), false), 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)
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("凭证".languageString(), "nil"), config: (true, true, (0,[])), frameh: UITableView.automaticDimension)
            newForms.append(rowCell)
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationAddImagesCell>.init(data: picArr, config: (false, true, 3), frameh: 76) {[weak self] back in
                guard let weakSelf = self else { return }
                if let data = back as? (Int, Int) {
                    switch data.0 {
                    case 1:
                        weakSelf.picArr.remove(at: data.1)
                        weakSelf.picker.remove(data.1)
                        weakSelf.makeForms()
                    case 2:
                        weakSelf.showImages(data.1)
                    case 3:
                        weakSelf.picker.showPhoto(weakSelf.picker.list.count) {[weak self] in
                            guard let strongSelf = self else { return }
                            strongSelf.requstUploadImages()
                            strongSelf.makeForms()
                        }
                    default:
                        break
                    }
                }
            }
            newForms.append(rowCell)
        }
        newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        
        for (i, item) in returnList.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.oldPartsName, code: item.oldPartsCode)
            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_OldPartsToBeReturnedList.Parts, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<PartsApplyOperationAmountsCell>.init(data: (data.qty, data.returnQty, "", ""), config: ("待退回量".languageString(), "已退回量".languageString(), "", ""),  frameh: 68)
        return [rowCell]
    }
    
    func makeQuantityCellForm(data:M_OldPartsToBeReturnedList.Parts,idx:Int) -> [TCCellBaseProtocol] {
        let maxQty1 = data.qty.intValue()
        let maxQty2 = data.returnQty.intValue()
        let maxQty = maxQty1 - maxQty2
        let rowCell = TCFormCellModel<PartsApplyOperationQuantityCell>.init(data: ("\("本次退回".languageString())：", data.num, 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.returnList[idx].num = 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 OldPartsConfirmReturnVm {
    
    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.setDicData(str, dic: dic)
            
        }.show(CD.visibleVC!)
    }
    
    func setDicData(_ str:String, dic:[String:Any]) {
        switch str {
        case "配送方式":
            deliverType = dic.stringValue(forKey: "id")
            deliverTypeName = dic.stringValue(forKey: "name")
        case "物流公司":
            deliverCompany = dic.stringValue(forKey: "id")
            deliverCompanyName = dic.stringValue(forKey: "name")
        default:
            break
        }
       self.makeForms()
    }
}

extension OldPartsConfirmReturnVm {
    
    func createPartsReturn() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["deliverType"] = deliverType
        par["deliverTypeName"] = deliverTypeName
        par["deliverCompany"] = deliverCompany
        par["deliverCompanyName"] = deliverCompanyName
        par["deliverNo"] = deliverNo
        par["deliverRemark"] = deliverRemark
        par["returnList"] = returnList.compactMap({$0.jsonValue()})
        for (i, item) in picArr.enumerated() {
            switch i {
            case 0:
                par["pic1"] = kGetPicUrl(item.imageUrl)
            case 1:
                par["pic2"] = kGetPicUrl(item.imageUrl)
            case 2:
                par["pic3"] = kGetPicUrl(item.imageUrl)
            default:
                break
            }
        }
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/partsDo/createPartsReturn",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()
    }
}

extension OldPartsConfirmReturnVm {
    func showImages(_ idx:Int = 0) {
        let imgArr:[(String,UIImage?)] = picArr.compactMap { ($0.imageUrl, $0.image) }
        var photos:[GKPhoto] = []
        for item in imgArr {
            let  photo = GKPhoto()
            if !item.0.isEmpty {
                photo.url = URL(string: item.0)!
            }
            if item.1 != nil {
                photo.image = item.1
            }
            photos.append(photo)
        }
        let browser = GKPhotoBrowser(photos: photos, currentIndex: idx)
        browser.showStyle = .none
        browser.modalPresentationStyle = .overFullScreen
        browser.show(fromVC: CD.visibleVC!)
    }
    
    func requstUploadImages(){
        let images:[TWImagePicker.Model] = picker.list
    
        if images.isEmpty { return }
        for (i,item) in images.enumerated() {
            let cNet = TWOCNetwork(url: "/admin/sys-file/upload",andParam: [:])
            cNet.successCall = { [weak self] (result) in
                guard let weakSelf = self else { return }
                if let data = result["data"] as? [String:Any] {
                    let iconUrl = kGetServerPicUrl(data.stringValue(forKey: "url"))
                    weakSelf.picker.list[i].uploadurl = iconUrl
                    weakSelf.picker.list[i].isupload = true
                    weakSelf.picArr = weakSelf.picker.list.compactMap({TCFormImageModel(imageUrl: $0.uploadurl, image: $0.image)})
                    weakSelf.makeForms()
                }else{
                    hud_error("请求出错了，请稍后再试~".languageString())
                }
            }
            cNet.failCall = {(errorTag,errorStr) in
                hud_error(errorStr)
            }
            cNet.upLoad(item.image!)
        }
    }
}
