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

import Foundation

class PartsApplySignVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    var callBack:((Bool)->Void)?
    
    var applyId = ""
    
    var partsList:[M_PartsApplyDetail.Parts] = []
    
    var picArr:[TCFormImageModel] = []
    
    lazy var picker:TWImagePicker = {
        let pp = TWImagePicker()
        pp.maxPhotoCount = 3
        pp.isSheet = true
        return pp
    }()
}

extension PartsApplySignVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        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)
        
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("签收凭证".languageString(), "nil"), config: (true, true, (8,[.topLeft, .topRight])), 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)
        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.applyQty, data.checkQty, data.outQty, data.getQty), config: ("申请数量".languageString(), "审核数量".languageString(), "发货数量".languageString(), "已签收量".languageString()),  frameh: 136)
        return [rowCell]
    }
    
    func makeQuantityCellForm(data:M_PartsApplyDetail.Parts,idx:Int) -> [TCCellBaseProtocol] {
        let maxQty = data.outQty.intValue() - data.getQty.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 PartsApplySignVm {
    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!)
        }
    }
}

extension PartsApplySignVm {
    
    func requestApplySign() {
        var par:[String:Any] = [:]
        par["applyId"] = applyId
        par["partsList"] = partsList.compactMap({$0.operationJsonValue(typeStr: "getQty")})
        par["pic1"] = ""
        par["pic2"] = ""
        par["pic3"] = ""
        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/applySign",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()
    }
}

