//
//  OrderComplainHandlingVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/12.
//

import Foundation

class OrderComplainHandlingVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    var viewType:ComplainType = .complain
    
    var orderId = ""
    var content = ""        //申诉内容(操作为提交申诉时必填)
    
    var checkType = 1          //审核结果:1同意;2不同意
    
    var picArr:[TCFormImageModel] = []
    
    lazy var picker:TWImagePicker = {
        let pp = TWImagePicker()
        pp.maxPhotoCount = 3
        pp.isSheet = true
        return pp
    }()
}

extension OrderComplainHandlingVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(height: 8)
        let isComplain = viewType == .complain
        if !isComplain {
            do{
                let rowCell = TCFormCellModel<OrderOperationSwitchCell>.init(data: ("审核结果".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 txt = isComplain ? "申诉内容".languageString() : "工单申诉审核内容".languageString()
            let rowCell = TCFormCellModel<OrderOperationRemarkVCell>.init(data: (txt, content), config: (isComplain ? (8, [.topLeft, .topRight]) : (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 txt = isComplain ? "申诉凭证".languageString() : "审核凭证".languageString()
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: (txt, "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 OrderComplainHandlingVm {
    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 OrderComplainHandlingVm {
    //doType:操作类型:1放弃申诉;2提交申诉
    func requestComplain(_ doType:Int) {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["doType"] = doType
        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/complain",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()
    }
    
    func requestComplainCheck() {
        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/complainCheck",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()
    }
}

