//
//  OrderFinishCheckVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/13.
//

import Foundation

class OrderFinishCheckVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var orderId = ""
    var content = ""        //审核备注
    
    var checkType = 1          //审核结果:1同意;2重新完工;3中止结算
    
    var picArr:[TCFormImageModel] = []
    
    lazy var picker:TWImagePicker = {
        let pp = TWImagePicker()
        pp.maxPhotoCount = 3
        pp.isSheet = true
        return pp
    }()
}

extension OrderFinishCheckVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 8)
        do{
            let rowCell = TCFormCellModel<OrderOperationSwitchCell>.init(data: ("审核结果".languageString(), "同意".languageString(), "重新完工".languageString(), "中止结算".languageString(), checkType), config: (false, (8, [.topLeft, .topRight])), frameh: UITableView.automaticDimension) { [weak self] back in
                guard let weakSelf = self else { return }
                if let tag = back as? Int {
                    weakSelf.checkType = tag
                    weakSelf.makeForms()
                }
            }
            newForms.append(rowCell)
        }
        do{
            let rowCell = TCFormCellModel<OrderOperationRemarkVCell>.init(data: ("审核备注".languageString(), content), config: ((0, []), false), frameh: 96) {[weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    weakSelf.content = 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)
        
        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]
    }
}

extension OrderFinishCheckVm {
    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 OrderFinishCheckVm {
    
    func requestFinishCheck() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["checkType"] = checkType
        par["content"] = content
        for (i, item) in picArr.enumerated() {
            switch i {
            case 0:
                par["fileUrl1"] = kGetPicUrl(item.imageUrl)
            case 1:
                par["fileUrl2"] = kGetPicUrl(item.imageUrl)
            case 2:
                par["fileUrl3"] = kGetPicUrl(item.imageUrl)
            default:
                break
            }
        }

        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/finishCheck",andParam: par)
        cNet.successCall = {(result) in
            hud_hidden()
            hud_succeed("操作成功~".languageString())
            CD.pop()
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
}

