//
//  OrderApplyReturnVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/1.
//

import Foundation

class OrderApplyReturnVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    var orderId = ""
    var callBack:((Bool)->Void)?
    
    var reasonList:[M_SelectType] = []
    var reason = M_SelectType()
    var remark = ""
    var picArr:[TCFormImageModel] = []
    
    lazy var picker:TWImagePicker = {
        let pp = TWImagePicker()
        pp.maxPhotoCount = 3
        pp.isSheet = true
        return pp
    }()
    
    lazy var upload:TWImagePickerUpload = {
        return TWImagePickerUpload()
    }()
    
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(type: .clear)
        do{
            let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: ("退单原因".languageString(), reason.name), config: (false, false, (8, [.topLeft, .topRight])), frameh: UITableView.automaticDimension, didSelect:  {
                self.getReturnTypeList()
            })
            newForms.append(rowCell)
        }
        
        do{
            let rowCell = TCFormCellModel<OrderOperationRemarkVCell>.init(data: ("退单描述".languageString(), remark), config: ((8, [.bottomLeft, .bottomRight]), true), frameh: 96) {[weak self] back in
                guard let weakSelf = self else { return }
                if let txt = back as? String {
                    weakSelf.remark = txt
                    weakSelf.makeForms()
                }
            }
            newForms.append(rowCell)
        }
        
        newForms += makeLineCellForm(type: .clear)
        newForms += makeLineCellForm(type: .white, corners: (8, [.layerMinXMinYCorner, .layerMaxXMinYCorner]), height: 12)
        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(type: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        
        forms = newForms
        reloadData?()
    }
}

extension OrderApplyReturnVm {
    enum LineCellType {
        case line
        case clear
        case white
    }
    func makeLineCellForm(type:LineCellType, corners:(CGFloat, CACornerMask)? = nil, hideLine:Bool? = nil, hideView:Bool? = nil, height:CGFloat? = nil) -> [TCCellBaseProtocol] {
        var corner:(CGFloat, CACornerMask) = (0,[])
        var isLineHidden = true
        var isViewHidden = false
        var hh:CGFloat = 12
        switch type {
        case .line:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? false
            isViewHidden = hideView ?? false
            hh = height ?? 13
        case .clear:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? true
            isViewHidden = hideView ?? true
            hh = height ?? 8
        case .white:
            corner = corners ?? (0, [])
            isLineHidden = hideLine ?? true
            isViewHidden = hideView ?? false
            hh = height ?? 8
        }
        let rowCell = TCFormCellModel<WorkbenchTitleCell>.init(data: "", config: (corner, isLineHidden, isViewHidden), frameh: hh)
        return [rowCell]
    }
}

extension OrderApplyReturnVm {
    func seletReturnType() {
        let dataArr = reasonList.compactMap { ($0.name,"") }
        TWSheetPicker.showActionSheet(titleStr: "请选择退单原因".languageString(), singleType: true, dataArr: dataArr) {[weak self] arr in
            guard let weakSelf = self else {return}
            guard !arr.isEmpty else {return}
            weakSelf.reason = weakSelf.reasonList[arr.first!]
            weakSelf.makeForms()
        }.show(CD.visibleVC!)
    }
    
    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!)
    }
}

extension OrderApplyReturnVm {
    func getReturnTypeList() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["type"] = 1
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/getReturnTypeList",andParam: par)
        cNet.successCall = { [weak self] (result) in
            hud_hidden()
            guard let weakSelf = self else { return }
            if let data = result["data"] as? [String:Any] {
                if let list = data["list"] as? [[String:Any]] {
                    weakSelf.reasonList = list.compactMap({M_SelectType($0)})
                    weakSelf.seletReturnType()
                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()

    }
    
    func submit() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["returnTypeId"] = reason.id
        par["remark"] = remark
        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/orderDo/back",andParam: par)
        cNet.successCall = {[weak self](result) in
            guard let weakSelf = self else { return }
            hud_succeed("操作成功~".languageString())
            weakSelf.callBack?(true)
            CD.pop()
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()

    }
    
////    http://fwptcloud.5mall.com/admin/sys-file/upload
//    func uploadImage() {
//        let images:[TWImagePicker.Model] = picker.list
//
//        if images.isEmpty { return }
////        let url = CD_Net.config.baseURL + "/m/file/upload.jhtml"
//        upload.uploadImages(images, urlkey: "iconurl", completion:  { [weak self](bool) in
//            guard let weakSelf = self else {return}
//            guard bool else { return }
//            weakSelf.picArr = weakSelf.picker.list.compactMap({TCFormImageModel(imageUrl: $0.uploadurl, image: $0.image)})
//            weakSelf.makeForms()
//        })
//    }
    
    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!)
        }
    }
}

