//
//  ProcessFeedbackVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/8/30.
//

import Foundation

class ProcessFeedbackVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    var orderId = ""
    
    var dispatchStatList:[M_SelectType] = []
    var dispatchStat = 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(), dispatchStat.name), config: (false, false, (8, [.topLeft, .topRight])), frameh: UITableView.automaticDimension, didSelect:  {
                self.getDispatchStat()
            })
            newForms.append(rowCell)
        }
        
//        do{
//            let rowCell = TCFormCellModel<OrderOperationRemarkVCell>.init(data: ("反馈描述", 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 += makeSelectCellForm(titleStr: "反馈描述".languageString(), infoStr: "nil", isHideLine: true, isHideArrow: true)
        do{
            let rowCell = TCFormCellModel<OrderOperationTextViewCell>.init(data: (remark), frameh: 104) {[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: .white, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        
        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 ProcessFeedbackVm {
    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]
    }
    
    func makeSelectCellForm(titleStr:String = "", infoStr:String = "", isHideLine:Bool = false, isHideArrow:Bool = false, corner:(CGFloat, UIRectCorner) = (0,[]), hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderOperationSelectCell>.init(data: (titleStr, infoStr), config: (isHideLine, isHideArrow, corner), frameh: hh ?? UITableView.automaticDimension)
        return [rowCell]
    }
}

extension ProcessFeedbackVm {
    func seletDispatchStat() {
        let dataArr = dispatchStatList.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.dispatchStat = weakSelf.dispatchStatList[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 ProcessFeedbackVm {
    func getDispatchStat() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/getDispatchStat",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.dispatchStatList = list.compactMap({M_SelectType($0)})
                    weakSelf.seletDispatchStat()
                }
            }
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()

    }
    
    func submit() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["dispatchStatName"] = dispatchStat.name
        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/doProcess",andParam: par)
        cNet.successCall = {(result) in
            hud_hidden()
            hud_succeed("操作成功~".languageString())
            CD.pop()
        }
        cNet.failCall = {(errorTag,errorStr) in
            hud_hidden()
            hud_error(errorStr)
        }
        cNet.postRequest()

    }
    
    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!)
        }
    }
}

struct M_SelectType {
    var id = ""
    var name = ""
    
    init(_ data:[String:Any] = [:]) {
        id = data.stringValue(forKey: "id")
        name = data.stringValue(forKey: "name")
    }
}
