//
//  OrderTeamAssistanceVm.swift
//  VattiCSS
//
//  Created by WZR on 2023/9/8.
//

import Foundation

class OrderTeamAssistanceVm: NSObject {
    var forms:[TCCellBaseProtocol] = []
    var reloadData:(()->())?
    
    var orderId = ""
    
    var helperList:[M_Helper] = []
    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()
    }()
}

extension OrderTeamAssistanceVm {
    func makeForms() {
        var newForms:[TCCellBaseProtocol] = []
        newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
        newForms += makeTitleCellForm(titleStr: "协助人信息".languageString(), statusStr: "新增协助人".languageString(), corner: helperList.isEmpty ? (8,.allCorners) : (8, [.topLeft, .topRight]), isShowArrow: true)
        for (i,item) in helperList.enumerated(){
            if i > 0 {
                newForms += makeLineCellForm(leftW: 12, rightW: 12, bgColor: .white, height: 8)
            }
            do{
                let rowCell = TCFormCellModel<OrderAssistPersonSelectedCell>.init(data: (item.pic, item.name, item.mobile), frameh: UITableView.automaticDimension) { [weak self] _ in
                    guard let weakSelf = self else { return }
                    weakSelf.helperList.remove(at: i)
                    weakSelf.makeForms()
                }
                newForms.append(rowCell)
            }
            if i == helperList.count - 1 {
                newForms += makeLineCellForm(leftW: 12, rightW: 12,bgColor: .white, backGroundColor: .clear, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
            }
        }
        
        
        newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
        newForms += makeTitleCellForm(titleStr: "备注信息".languageString(), statusStr: "", corner: (8, [.topLeft, .topRight]))
        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(leftW: 12, rightW: 12,bgColor: .white, backGroundColor: .clear, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 12)
        
        
        newForms += makeLineCellForm(bgColor: Config.color.hex("f8"), height: 8)
        newForms += makeTitleCellForm(titleStr: "图片".languageString(), statusStr: "", corner: (8, [.topLeft, .topRight]))
        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, backGroundColor: .clear, corners: (8, [.layerMinXMaxYCorner, .layerMaxXMaxYCorner]), height: 18)

        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 makeTitleCellForm(titleStr:String = "", statusStr:String = "", corner:(CGFloat, UIRectCorner) = (0,[]), isShowArrow:Bool = false, hh:CGFloat? = nil) -> [TCCellBaseProtocol] {
        let rowCell = TCFormCellModel<OrderDetailTitleCell>.init(data: (titleStr, statusStr), config: (corner, isShowArrow), frameh: hh ?? UITableView.automaticDimension) { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.selectHelper()
        }
        return [rowCell]
    }
    
    func selectHelper() {
        R_OrderAssistPerson.router(orderId, selIdList: helperList.compactMap({$0.id})) { [weak self] datas in
            guard let weakSelf = self else { return }
            let arr = datas.compactMap({M_Helper($0)})
            weakSelf.helperList += arr.filter({ item in
                !weakSelf.helperList.contains(where: {$0.id == item.id})
            })
            weakSelf.makeForms()
        }
    }
}

extension OrderTeamAssistanceVm {
    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 OrderTeamAssistanceVm {
    func requestData() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        hud_loading()
        let cNet = TWOCNetwork(url: "/app/v2/orderDo/helperList",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["helperList"] as? [[String:Any]] {
                    weakSelf.helperList = list.compactMap({M_Helper($0)})
                    weakSelf.makeForms()
                }
            }
        }
        cNet.failCall = {[weak self](errorTag,errorStr) in
            guard let weakSelf = self else { return }
            hud_hidden()
            hud_error(errorStr)
            weakSelf.makeForms()
        }
        cNet.postRequest()
    }
    
    func askForHelp() {
        var par:[String:Any] = [:]
        par["orderId"] = orderId
        par["remark"] = remark
        par["helperList"] = helperList.compactMap({$0.idValue()})
        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/help",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_error(errorStr)
            weakSelf.makeForms()
        }
        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!)
        }
    }
}

class M_Helper: NSObject {
    var id = ""          //协助人ID);
    var name = ""          //名称);
    var helperType = 0          //人员类型:0工程师;1服务商);
    var pic = ""
    var mobile = ""

    init(_ data:[String:Any] = [:]) {
        id = data.stringValue(forKey: "id")
        name = data.stringValue(forKey: "name")
        helperType = data.intValue(forKey: "helperType")
        pic = kGetServerPicUrl(data.stringValue(forKey: "pic"))
        mobile = data.stringValue(forKey: "mobile")
    }
    
    func idValue() -> [String:Any] {
        return ["id":id]
    }
}
